Adding Py best pratices flakes and pyupgrade

pull/725/head
ChethanUK 2 days ago
parent b408fafba8
commit b255ca3d39

@ -1,7 +1,10 @@
# Example usage # Example usage
from pathlib import Path from pathlib import Path
from swarms.structs.csv_to_agent import AgentLoader, AgentValidationError
from swarms.structs.csv_to_agent import (
AgentLoader,
AgentValidationError,
)
if __name__ == "__main__": if __name__ == "__main__":
# Example agent configurations # Example agent configurations

@ -1,11 +1,12 @@
import os import os
from dotenv import load_dotenv
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import ( from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT, FINANCIAL_AGENT_SYS_PROMPT,
) )
from dotenv import load_dotenv
load_dotenv() load_dotenv()

@ -1,8 +1,8 @@
from loguru import logger from loguru import logger
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.structs.graph_swarm import GraphSwarm from swarms.structs.graph_swarm import GraphSwarm
if __name__ == "__main__": if __name__ == "__main__":
try: try:
# Create agents # Create agents

@ -39,4 +39,4 @@ if __name__ == "__main__":
print(result_execute) print(result_execute)
except Exception as e: except Exception as e:
print(f"Error occurred: {str(e)}") print(f"Error occurred: {e!s}")

@ -1,8 +1,8 @@
import os import os
from swarms import Agent
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent
from swarms.structs.agents_available import showcase_available_agents from swarms.structs.agents_available import showcase_available_agents
# Get the OpenAI API key from the environment variable # Get the OpenAI API key from the environment variable

@ -1,10 +1,10 @@
import os import os
from swarm_models import OpenAIChat
from swarms import Agent
from fluid_api_agent.main import fluid_api_request
from dotenv import load_dotenv from dotenv import load_dotenv
from fluid_api_agent.main import fluid_api_request
from swarm_models import OpenAIChat
from swarms import Agent
load_dotenv() load_dotenv()
@ -82,9 +82,9 @@ def omni_api(task: str) -> str:
# Define the system prompt tailored for the API expert # Define the system prompt tailored for the API expert
API_AGENT_SYS_PROMPT = """ API_AGENT_SYS_PROMPT = """
You are a highly specialized financial API expert. You are a highly specialized financial API expert.
Your expertise lies in analyzing financial data, making investment recommendations, and Your expertise lies in analyzing financial data, making investment recommendations, and
interacting with APIs to retrieve, process, and present data effectively. interacting with APIs to retrieve, process, and present data effectively.
You use tools like 'omni_api' to fetch data dynamically, ensuring accuracy and up-to-date results. You use tools like 'omni_api' to fetch data dynamically, ensuring accuracy and up-to-date results.
Instructions: Instructions:

@ -1,8 +1,9 @@
from swarm_models import OpenAIChat
from swarms import Agent from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import ( from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT, FINANCIAL_AGENT_SYS_PROMPT,
) )
from swarm_models import OpenAIChat
model = OpenAIChat(model_name="gpt-4o") model = OpenAIChat(model_name="gpt-4o")

@ -3,11 +3,11 @@ import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from new_features_examples.async_executor import HighSpeedExecutor
from swarms import Agent from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import ( from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT, FINANCIAL_AGENT_SYS_PROMPT,
) )
from new_features_examples.async_executor import HighSpeedExecutor
load_dotenv() load_dotenv()

@ -2,11 +2,11 @@ import asyncio
import multiprocessing as mp import multiprocessing as mp
import time import time
from functools import partial from functools import partial
from typing import Any, Dict, Union from typing import Any, Optional, Union
class HighSpeedExecutor: class HighSpeedExecutor:
def __init__(self, num_processes: int = None): def __init__(self, num_processes: Optional[int] = None):
""" """
Initialize the executor with configurable number of processes. Initialize the executor with configurable number of processes.
If num_processes is None, it uses CPU count. If num_processes is None, it uses CPU count.
@ -45,7 +45,7 @@ class HighSpeedExecutor:
num_executions: int, num_executions: int,
*args: Any, *args: Any,
**kwargs: Any, **kwargs: Any,
) -> Dict[str, Union[int, float]]: ) -> dict[str, Union[int, float]]:
""" """
Execute the given function multiple times concurrently. Execute the given function multiple times concurrently.

@ -1,21 +1,20 @@
import asyncio import asyncio
from typing import List
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
from swarms.structs.agent import Agent
from swarms.structs.async_workflow import ( from swarms.structs.async_workflow import (
SpeakerConfig, SpeakerConfig,
SpeakerRole, SpeakerRole,
create_default_workflow, create_default_workflow,
run_workflow_with_retry, run_workflow_with_retry,
) )
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
from swarms.structs.agent import Agent
async def create_specialized_agents() -> List[Agent]: async def create_specialized_agents() -> list[Agent]:
"""Create a set of specialized agents for financial analysis""" """Create a set of specialized agents for financial analysis"""
# Base model configuration # Base model configuration
@ -165,7 +164,7 @@ async def main():
print(value) print(value)
except Exception as e: except Exception as e:
print(f"Workflow failed: {str(e)}") print(f"Workflow failed: {e!s}")
finally: finally:
await workflow.cleanup() await workflow.cleanup()

@ -1,7 +1,7 @@
import json import json
import os import os
from contextlib import suppress from contextlib import suppress
from typing import Any, Callable, Dict, Optional, Type, Union from typing import Any, Callable, Optional, Union
from dotenv import load_dotenv from dotenv import load_dotenv
from pydantic import BaseModel, Field, ValidationError, create_model from pydantic import BaseModel, Field, ValidationError, create_model
@ -10,7 +10,7 @@ from swarm_models.openai_function_caller import OpenAIFunctionCaller
class DynamicParser: class DynamicParser:
@staticmethod @staticmethod
def extract_fields(model: Type[BaseModel]) -> Dict[str, Any]: def extract_fields(model: type[BaseModel]) -> dict[str, Any]:
return { return {
field_name: ( field_name: (
field.annotation, field.annotation,
@ -21,8 +21,8 @@ class DynamicParser:
@staticmethod @staticmethod
def create_partial_model( def create_partial_model(
model: Type[BaseModel], data: Dict[str, Any] model: type[BaseModel], data: dict[str, Any]
) -> Type[BaseModel]: ) -> type[BaseModel]:
fields = { fields = {
field_name: ( field_name: (
field.annotation, field.annotation,
@ -35,7 +35,7 @@ class DynamicParser:
@classmethod @classmethod
def parse( def parse(
cls, data: Union[str, Dict[str, Any]], model: Type[BaseModel] cls, data: Union[str, dict[str, Any]], model: type[BaseModel]
) -> Optional[BaseModel]: ) -> Optional[BaseModel]:
if isinstance(data, str): if isinstance(data, str):
try: try:
@ -88,7 +88,7 @@ class Command(BaseModel):
..., ...,
description="Command name to execute from the provided list of commands.", description="Command name to execute from the provided list of commands.",
) )
args: Dict[str, Any] = Field( args: dict[str, Any] = Field(
..., description="Arguments required to execute the command." ..., description="Arguments required to execute the command."
) )
@ -134,9 +134,9 @@ def task_complete_command(reason: str):
# Dynamic command execution # Dynamic command execution
def execute_command(name: str, args: Dict[str, Any]): def execute_command(name: str, args: dict[str, Any]):
"""Dynamically execute a command based on its name and arguments.""" """Dynamically execute a command based on its name and arguments."""
command_map: Dict[str, Callable] = { command_map: dict[str, Callable] = {
"fluid_api": lambda **kwargs: fluid_api_command( "fluid_api": lambda **kwargs: fluid_api_command(
task=kwargs.get("task") task=kwargs.get("task")
), ),
@ -157,8 +157,8 @@ def execute_command(name: str, args: Dict[str, Any]):
def parse_and_execute_command( def parse_and_execute_command(
response: Union[str, Dict[str, Any]], response: Union[str, dict[str, Any]],
base_model: Type[BaseModel] = AgentResponse, base_model: type[BaseModel] = AgentResponse,
) -> Any: ) -> Any:
"""Enhanced command parser with flexible input handling""" """Enhanced command parser with flexible input handling"""
parsed = DynamicParser.parse(response, base_model) parsed = DynamicParser.parse(response, base_model)
@ -197,7 +197,7 @@ Your role is to make decisions and complete tasks independently without seeking
### COMMANDS: ### COMMANDS:
1. Fluid API: "fluid_api", args: "method": "<GET/POST/...>", "url": "<url>", "headers": "<headers>", "body": "<payload>" 1. Fluid API: "fluid_api", args: "method": "<GET/POST/...>", "url": "<url>", "headers": "<headers>", "body": "<payload>"
18. Send Tweet: "send_tweet", args: "text": "<text>" 18. Send Tweet: "send_tweet", args: "text": "<text>"
19. Do Nothing: "do_nothing", args: 19. Do Nothing: "do_nothing", args:
20. Task Complete (Shutdown): "task_complete", args: "reason": "<reason>" 20. Task Complete (Shutdown): "task_complete", args: "reason": "<reason>"
### RESOURCES: ### RESOURCES:

@ -1,7 +1,9 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import Agent
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent
from swarms.structs.swarm_router import SwarmRouter from swarms.structs.swarm_router import SwarmRouter
load_dotenv() load_dotenv()

@ -16,15 +16,15 @@ model = OpenAIChat(
delaware_ccorp_agent = Agent( delaware_ccorp_agent = Agent(
agent_name="Delaware-CCorp-Hiring-Agent", agent_name="Delaware-CCorp-Hiring-Agent",
system_prompt=""" system_prompt="""
Create a comprehensive hiring description for a Delaware C Corporation, Create a comprehensive hiring description for a Delaware C Corporation,
including all relevant laws and regulations, such as the Delaware General including all relevant laws and regulations, such as the Delaware General
Corporation Law (DGCL) and the Delaware Corporate Law. Ensure the description Corporation Law (DGCL) and the Delaware Corporate Law. Ensure the description
covers the requirements for hiring employees, contractors, and officers, covers the requirements for hiring employees, contractors, and officers,
including the necessary paperwork, tax obligations, and benefits. Also, including the necessary paperwork, tax obligations, and benefits. Also,
outline the procedures for compliance with Delaware's employment laws, outline the procedures for compliance with Delaware's employment laws,
including anti-discrimination laws, workers' compensation, and unemployment including anti-discrimination laws, workers' compensation, and unemployment
insurance. Provide guidance on how to navigate the complexities of Delaware's insurance. Provide guidance on how to navigate the complexities of Delaware's
corporate law and ensure that all hiring practices are in compliance with corporate law and ensure that all hiring practices are in compliance with
state and federal regulations. state and federal regulations.
""", """,
llm=model, llm=model,
@ -41,17 +41,17 @@ delaware_ccorp_agent = Agent(
indian_foreign_agent = Agent( indian_foreign_agent = Agent(
agent_name="Indian-Foreign-Hiring-Agent", agent_name="Indian-Foreign-Hiring-Agent",
system_prompt=""" system_prompt="""
Create a comprehensive hiring description for an Indian or foreign country, Create a comprehensive hiring description for an Indian or foreign country,
including all relevant laws and regulations, such as the Indian Contract Act, including all relevant laws and regulations, such as the Indian Contract Act,
the Indian Labour Laws, and the Foreign Exchange Management Act (FEMA). the Indian Labour Laws, and the Foreign Exchange Management Act (FEMA).
Ensure the description covers the requirements for hiring employees, Ensure the description covers the requirements for hiring employees,
contractors, and officers, including the necessary paperwork, tax obligations, contractors, and officers, including the necessary paperwork, tax obligations,
and benefits. Also, outline the procedures for compliance with Indian and and benefits. Also, outline the procedures for compliance with Indian and
foreign employment laws, including anti-discrimination laws, workers' foreign employment laws, including anti-discrimination laws, workers'
compensation, and unemployment insurance. Provide guidance on how to navigate compensation, and unemployment insurance. Provide guidance on how to navigate
the complexities of Indian and foreign corporate law and ensure that all hiring the complexities of Indian and foreign corporate law and ensure that all hiring
practices are in compliance with state and federal regulations. Consider the practices are in compliance with state and federal regulations. Consider the
implications of hiring foreign nationals and the requirements for obtaining implications of hiring foreign nationals and the requirements for obtaining
necessary visas and work permits. necessary visas and work permits.
""", """,
llm=model, llm=model,
@ -69,19 +69,19 @@ indian_foreign_agent = Agent(
agents = [delaware_ccorp_agent, indian_foreign_agent] agents = [delaware_ccorp_agent, indian_foreign_agent]
tasks = [ tasks = [
""" """
Create a comprehensive hiring description for an Agent Engineer, including Create a comprehensive hiring description for an Agent Engineer, including
required skills and responsibilities. Ensure the description covers the required skills and responsibilities. Ensure the description covers the
necessary technical expertise, such as proficiency in AI/ML frameworks, necessary technical expertise, such as proficiency in AI/ML frameworks,
programming languages, and data structures. Outline the key responsibilities, programming languages, and data structures. Outline the key responsibilities,
including designing and developing AI agents, integrating with existing systems, including designing and developing AI agents, integrating with existing systems,
and ensuring scalability and performance. and ensuring scalability and performance.
""", """,
""" """
Generate a detailed job description for a Prompt Engineer, including Generate a detailed job description for a Prompt Engineer, including
required skills and responsibilities. Ensure the description covers the required skills and responsibilities. Ensure the description covers the
necessary technical expertise, such as proficiency in natural language processing, necessary technical expertise, such as proficiency in natural language processing,
machine learning, and software development. Outline the key responsibilities, machine learning, and software development. Outline the key responsibilities,
including designing and optimizing prompts for AI systems, ensuring prompt including designing and optimizing prompts for AI systems, ensuring prompt
quality and consistency, and collaborating with cross-functional teams. quality and consistency, and collaborating with cross-functional teams.
""", """,
] ]

@ -16,15 +16,15 @@ model = OpenAIChat(
delaware_ccorp_agent = Agent( delaware_ccorp_agent = Agent(
agent_name="Delaware-CCorp-Hiring-Agent", agent_name="Delaware-CCorp-Hiring-Agent",
system_prompt=""" system_prompt="""
Create a comprehensive hiring description for a Delaware C Corporation, Create a comprehensive hiring description for a Delaware C Corporation,
including all relevant laws and regulations, such as the Delaware General including all relevant laws and regulations, such as the Delaware General
Corporation Law (DGCL) and the Delaware Corporate Law. Ensure the description Corporation Law (DGCL) and the Delaware Corporate Law. Ensure the description
covers the requirements for hiring employees, contractors, and officers, covers the requirements for hiring employees, contractors, and officers,
including the necessary paperwork, tax obligations, and benefits. Also, including the necessary paperwork, tax obligations, and benefits. Also,
outline the procedures for compliance with Delaware's employment laws, outline the procedures for compliance with Delaware's employment laws,
including anti-discrimination laws, workers' compensation, and unemployment including anti-discrimination laws, workers' compensation, and unemployment
insurance. Provide guidance on how to navigate the complexities of Delaware's insurance. Provide guidance on how to navigate the complexities of Delaware's
corporate law and ensure that all hiring practices are in compliance with corporate law and ensure that all hiring practices are in compliance with
state and federal regulations. state and federal regulations.
""", """,
llm=model, llm=model,
@ -41,17 +41,17 @@ delaware_ccorp_agent = Agent(
indian_foreign_agent = Agent( indian_foreign_agent = Agent(
agent_name="Indian-Foreign-Hiring-Agent", agent_name="Indian-Foreign-Hiring-Agent",
system_prompt=""" system_prompt="""
Create a comprehensive hiring description for an Indian or foreign country, Create a comprehensive hiring description for an Indian or foreign country,
including all relevant laws and regulations, such as the Indian Contract Act, including all relevant laws and regulations, such as the Indian Contract Act,
the Indian Labour Laws, and the Foreign Exchange Management Act (FEMA). the Indian Labour Laws, and the Foreign Exchange Management Act (FEMA).
Ensure the description covers the requirements for hiring employees, Ensure the description covers the requirements for hiring employees,
contractors, and officers, including the necessary paperwork, tax obligations, contractors, and officers, including the necessary paperwork, tax obligations,
and benefits. Also, outline the procedures for compliance with Indian and and benefits. Also, outline the procedures for compliance with Indian and
foreign employment laws, including anti-discrimination laws, workers' foreign employment laws, including anti-discrimination laws, workers'
compensation, and unemployment insurance. Provide guidance on how to navigate compensation, and unemployment insurance. Provide guidance on how to navigate
the complexities of Indian and foreign corporate law and ensure that all hiring the complexities of Indian and foreign corporate law and ensure that all hiring
practices are in compliance with state and federal regulations. Consider the practices are in compliance with state and federal regulations. Consider the
implications of hiring foreign nationals and the requirements for obtaining implications of hiring foreign nationals and the requirements for obtaining
necessary visas and work permits. necessary visas and work permits.
""", """,
llm=model, llm=model,
@ -69,19 +69,19 @@ indian_foreign_agent = Agent(
agents = [delaware_ccorp_agent, indian_foreign_agent] agents = [delaware_ccorp_agent, indian_foreign_agent]
tasks = [ tasks = [
""" """
Create a comprehensive hiring description for an Agent Engineer, including Create a comprehensive hiring description for an Agent Engineer, including
required skills and responsibilities. Ensure the description covers the required skills and responsibilities. Ensure the description covers the
necessary technical expertise, such as proficiency in AI/ML frameworks, necessary technical expertise, such as proficiency in AI/ML frameworks,
programming languages, and data structures. Outline the key responsibilities, programming languages, and data structures. Outline the key responsibilities,
including designing and developing AI agents, integrating with existing systems, including designing and developing AI agents, integrating with existing systems,
and ensuring scalability and performance. and ensuring scalability and performance.
""", """,
""" """
Generate a detailed job description for a Prompt Engineer, including Generate a detailed job description for a Prompt Engineer, including
required skills and responsibilities. Ensure the description covers the required skills and responsibilities. Ensure the description covers the
necessary technical expertise, such as proficiency in natural language processing, necessary technical expertise, such as proficiency in natural language processing,
machine learning, and software development. Outline the key responsibilities, machine learning, and software development. Outline the key responsibilities,
including designing and optimizing prompts for AI systems, ensuring prompt including designing and optimizing prompts for AI systems, ensuring prompt
quality and consistency, and collaborating with cross-functional teams. quality and consistency, and collaborating with cross-functional teams.
""", """,
] ]

@ -1,4 +1,5 @@
import requests import requests
from swarms import Agent from swarms import Agent
# Define the system prompt specialized for $Swarms # Define the system prompt specialized for $Swarms

@ -1,8 +1,9 @@
import asyncio import asyncio
import aiohttp
from typing import Dict, List, Optional
from datetime import datetime from datetime import datetime
from statistics import mean, median from statistics import mean, median
from typing import Optional
import aiohttp
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
@ -121,7 +122,7 @@ class MultiExchangeDataFetcher:
"birdeye": "https://public-api.birdeye.so/public", # Using Birdeye instead of Jupiter "birdeye": "https://public-api.birdeye.so/public", # Using Birdeye instead of Jupiter
} }
async def fetch_data(self, url: str) -> Optional[Dict]: async def fetch_data(self, url: str) -> Optional[dict]:
"""Generic async function to fetch data from APIs with error handling""" """Generic async function to fetch data from APIs with error handling"""
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
try: try:
@ -136,10 +137,10 @@ class MultiExchangeDataFetcher:
print(f"Timeout while fetching from {url}") print(f"Timeout while fetching from {url}")
return None return None
except Exception as e: except Exception as e:
print(f"Error fetching from {url}: {str(e)}") print(f"Error fetching from {url}: {e!s}")
return None return None
async def get_coingecko_data(self) -> Optional[Dict]: async def get_coingecko_data(self) -> Optional[dict]:
"""Fetch $Swarms data from CoinGecko""" """Fetch $Swarms data from CoinGecko"""
try: try:
url = f"{self.base_urls['coingecko']}/simple/price" url = f"{self.base_urls['coingecko']}/simple/price"
@ -160,10 +161,10 @@ class MultiExchangeDataFetcher:
} }
return None return None
except Exception as e: except Exception as e:
print(f"Error processing CoinGecko data: {str(e)}") print(f"Error processing CoinGecko data: {e!s}")
return None return None
async def get_dexscreener_data(self) -> Optional[Dict]: async def get_dexscreener_data(self) -> Optional[dict]:
"""Fetch $Swarms data from DexScreener""" """Fetch $Swarms data from DexScreener"""
try: try:
url = ( url = (
@ -179,10 +180,10 @@ class MultiExchangeDataFetcher:
} }
return None return None
except Exception as e: except Exception as e:
print(f"Error processing DexScreener data: {str(e)}") print(f"Error processing DexScreener data: {e!s}")
return None return None
async def get_birdeye_data(self) -> Optional[Dict]: async def get_birdeye_data(self) -> Optional[dict]:
"""Fetch $Swarms data from Birdeye""" """Fetch $Swarms data from Birdeye"""
try: try:
# Example Birdeye endpoint - replace ADDRESS with actual Swarms token address # Example Birdeye endpoint - replace ADDRESS with actual Swarms token address
@ -201,12 +202,12 @@ class MultiExchangeDataFetcher:
} }
return None return None
except Exception as e: except Exception as e:
print(f"Error processing Birdeye data: {str(e)}") print(f"Error processing Birdeye data: {e!s}")
return None return None
def aggregate_data( def aggregate_data(
self, data_points: List[Optional[Dict]] self, data_points: list[Optional[dict]]
) -> Dict: ) -> dict:
"""Aggregate data from multiple sources with null checking""" """Aggregate data from multiple sources with null checking"""
prices = [] prices = []
volumes = [] volumes = []
@ -297,9 +298,9 @@ async def answer_swarms_query(query: str) -> str:
) )
return swarms_agent.run(full_query) return swarms_agent.run(full_query)
except Exception as e: except Exception as e:
print(f"Error in answer_swarms_query: {str(e)}") print(f"Error in answer_swarms_query: {e!s}")
return ( return (
f"An error occurred while processing your query: {str(e)}" f"An error occurred while processing your query: {e!s}"
) )

@ -1,5 +1,6 @@
import pandas as pd
import json import json
import pandas as pd
from loguru import logger from loguru import logger

@ -1,15 +1,17 @@
import os
from swarms import Agent
from swarm_models import OpenAIChat
from web3 import Web3
from typing import Dict, Optional, Any
from datetime import datetime
import asyncio import asyncio
from loguru import logger
from dotenv import load_dotenv
import csv import csv
import requests import os
import time import time
from datetime import datetime
from typing import Any, Optional
import requests
from dotenv import load_dotenv
from loguru import logger
from swarm_models import OpenAIChat
from web3 import Web3
from swarms import Agent
BLOCKCHAIN_AGENT_PROMPT = """ BLOCKCHAIN_AGENT_PROMPT = """
You are an expert blockchain and cryptocurrency analyst with deep knowledge of Ethereum markets and DeFi ecosystems. You are an expert blockchain and cryptocurrency analyst with deep knowledge of Ethereum markets and DeFi ecosystems.
@ -110,7 +112,7 @@ class EthereumAnalyzer:
) )
return float(response.json()["ethereum"]["usd"]) return float(response.json()["ethereum"]["usd"])
except Exception as e: except Exception as e:
logger.error(f"Error fetching ETH price: {str(e)}") logger.error(f"Error fetching ETH price: {e!s}")
return 0.0 return 0.0
def update_eth_price(self): def update_eth_price(self):
@ -143,7 +145,7 @@ class EthereumAnalyzer:
async def analyze_transaction( async def analyze_transaction(
self, tx_hash: str self, tx_hash: str
) -> Optional[Dict[str, Any]]: ) -> Optional[dict[str, Any]]:
"""Analyze a single transaction.""" """Analyze a single transaction."""
try: try:
tx = self.w3.eth.get_transaction(tx_hash) tx = self.w3.eth.get_transaction(tx_hash)
@ -191,11 +193,11 @@ class EthereumAnalyzer:
except Exception as e: except Exception as e:
logger.error( logger.error(
f"Error analyzing transaction {tx_hash}: {str(e)}" f"Error analyzing transaction {tx_hash}: {e!s}"
) )
return None return None
def prepare_analysis_prompt(self, tx_data: Dict[str, Any]) -> str: def prepare_analysis_prompt(self, tx_data: dict[str, Any]) -> str:
"""Prepare detailed analysis prompt including price context.""" """Prepare detailed analysis prompt including price context."""
value_usd = tx_data["value_usd"] value_usd = tx_data["value_usd"]
eth_price = tx_data["eth_price"] eth_price = tx_data["eth_price"]
@ -220,7 +222,7 @@ Analyze market impact, patterns, risks, and strategic implications."""
return prompt return prompt
def save_to_csv(self, tx_data: Dict[str, Any], ai_analysis: str): def save_to_csv(self, tx_data: dict[str, Any], ai_analysis: str):
"""Save transaction data and analysis to CSV.""" """Save transaction data and analysis to CSV."""
row = [ row = [
tx_data["timestamp"], tx_data["timestamp"],
@ -288,7 +290,7 @@ Analyze market impact, patterns, risks, and strategic implications."""
await asyncio.sleep(1) # Wait for next block await asyncio.sleep(1) # Wait for next block
except Exception as e: except Exception as e:
logger.error(f"Error in monitoring loop: {str(e)}") logger.error(f"Error in monitoring loop: {e!s}")
await asyncio.sleep(1) await asyncio.sleep(1)

@ -1,14 +1,15 @@
import os
import asyncio import asyncio
from swarms import Agent import os
from swarm_models import OpenAIChat
import time import time
import psutil import psutil
from dotenv import load_dotenv
from swarm_models import OpenAIChat
from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import ( from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT, FINANCIAL_AGENT_SYS_PROMPT,
) )
from dotenv import load_dotenv
load_dotenv() load_dotenv()

@ -1,6 +1,5 @@
from swarms.structs.tree_swarm import ForestSwarm, Tree, TreeAgent from swarms.structs.tree_swarm import ForestSwarm, Tree, TreeAgent
agents_tree1 = [ agents_tree1 = [
TreeAgent( TreeAgent(
system_prompt="Stock Analysis Agent", system_prompt="Stock Analysis Agent",

@ -84,7 +84,7 @@ class LlamaIndexDB:
f"Successfully indexed documents from {self.data_dir}" f"Successfully indexed documents from {self.data_dir}"
) )
except Exception as e: except Exception as e:
logger.error(f"Error indexing documents: {str(e)}") logger.error(f"Error indexing documents: {e!s}")
raise raise
def query(self, query: str, **kwargs) -> str: def query(self, query: str, **kwargs) -> str:
@ -115,7 +115,7 @@ class LlamaIndexDB:
logger.info(f"Successfully queried: {query}") logger.info(f"Successfully queried: {query}")
return str(response) return str(response)
except Exception as e: except Exception as e:
logger.error(f"Error during query: {str(e)}") logger.error(f"Error during query: {e!s}")
raise raise

@ -1,4 +1,5 @@
import os import os
import google.generativeai as genai import google.generativeai as genai
from loguru import logger from loguru import logger

@ -1,6 +1,8 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, GroupChat, expertise_based from swarms import Agent, GroupChat, expertise_based
if __name__ == "__main__": if __name__ == "__main__":

@ -1,6 +1,8 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, GroupChat from swarms import Agent, GroupChat
if __name__ == "__main__": if __name__ == "__main__":

@ -1,6 +1,8 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, GroupChat from swarms import Agent, GroupChat
if __name__ == "__main__": if __name__ == "__main__":

@ -1,8 +1,9 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, GroupChat
from swarms import Agent, GroupChat
if __name__ == "__main__": if __name__ == "__main__":

@ -1,6 +1,5 @@
from swarms import Agent from swarms import Agent
# Claims Processing Agent system prompt # Claims Processing Agent system prompt
CLAIMS_PROCESSING_AGENT_SYS_PROMPT = """ CLAIMS_PROCESSING_AGENT_SYS_PROMPT = """
Here's an extended and detailed system prompt for the **Claims Processing Agent**, incorporating reasoning steps, output format, and examples for structured responses: Here's an extended and detailed system prompt for the **Claims Processing Agent**, incorporating reasoning steps, output format, and examples for structured responses:

@ -1,7 +1,7 @@
import asyncio import asyncio
from dataclasses import dataclass from dataclasses import dataclass
from enum import Enum from enum import Enum
from typing import List, Optional from typing import Optional
from swarms import Agent from swarms import Agent
@ -22,11 +22,11 @@ class InsuranceProduct:
name: str name: str
type: InsuranceType type: InsuranceType
description: str description: str
coverage: List[str] coverage: list[str]
price_range: str price_range: str
min_coverage: float min_coverage: float
max_coverage: float max_coverage: float
payment_options: List[str] payment_options: list[str]
waiting_period: str waiting_period: str
available: bool available: bool
@ -137,7 +137,7 @@ class InsuranceBot:
self.agent = Agent( self.agent = Agent(
agent_name="LATAM-Insurance-Agent", agent_name="LATAM-Insurance-Agent",
system_prompt="""You are a specialized insurance assistant for Latin America's leading insurance provider. system_prompt="""You are a specialized insurance assistant for Latin America's leading insurance provider.
Key Responsibilities: Key Responsibilities:
1. Product Information: 1. Product Information:
- Explain our comprehensive insurance portfolio - Explain our comprehensive insurance portfolio
@ -150,7 +150,7 @@ Key Responsibilities:
- Handle claims information - Handle claims information
- Assist with payment options - Assist with payment options
- Locate nearest offices - Locate nearest offices
3. Cultural Considerations: 3. Cultural Considerations:
- Communicate in Spanish and Portuguese - Communicate in Spanish and Portuguese
- Understand LATAM insurance regulations - Understand LATAM insurance regulations
@ -179,7 +179,7 @@ When discussing products, always reference accurate prices, coverage amounts, an
# Use agent to provide personalized product recommendations # Use agent to provide personalized product recommendations
return await self.agent.run( return await self.agent.run(
"""Por favor ayude al cliente a elegir un producto: """Por favor ayude al cliente a elegir un producto:
Productos disponibles: Productos disponibles:
- AUTO001: Seguro Auto Total - AUTO001: Seguro Auto Total
- LIFE001: Vida Protegida Plus - LIFE001: Vida Protegida Plus
@ -290,7 +290,7 @@ Explique brevemente cada uno y solicite información sobre sus necesidades espec
Estado: {'Disponible' if product.available else 'No disponible'} Estado: {'Disponible' if product.available else 'No disponible'}
""" """
def handle_main_menu(self) -> List[str]: def handle_main_menu(self) -> list[str]:
"""Return main menu options""" """Return main menu options"""
return [ return [
"1. Consultar productos de seguro", "1. Consultar productos de seguro",

@ -1,12 +1,13 @@
from typing import List, Dict import asyncio
import json
from dataclasses import dataclass from dataclasses import dataclass
from datetime import datetime from datetime import datetime
import asyncio from pathlib import Path
import aiohttp import aiohttp
from loguru import logger from loguru import logger
from swarms import Agent from swarms import Agent
from pathlib import Path
import json
@dataclass @dataclass
@ -39,7 +40,7 @@ class DataFetcher:
async def get_market_data( async def get_market_data(
self, limit: int = 20 self, limit: int = 20
) -> List[CryptoData]: ) -> list[CryptoData]:
"""Fetch market data for top cryptocurrencies""" """Fetch market data for top cryptocurrencies"""
await self._init_session() await self._init_session()
@ -91,7 +92,7 @@ class DataFetcher:
) )
except (ValueError, TypeError) as e: except (ValueError, TypeError) as e:
logger.error( logger.error(
f"Error processing coin data: {str(e)}" f"Error processing coin data: {e!s}"
) )
continue continue
@ -101,7 +102,7 @@ class DataFetcher:
return crypto_data return crypto_data
except Exception as e: except Exception as e:
logger.error(f"Exception in get_market_data: {str(e)}") logger.error(f"Exception in get_market_data: {e!s}")
return [] return []
@ -111,7 +112,7 @@ class CryptoSwarmSystem:
self.data_fetcher = DataFetcher() self.data_fetcher = DataFetcher()
logger.info("Crypto Swarm System initialized") logger.info("Crypto Swarm System initialized")
def _initialize_agents(self) -> Dict[str, Agent]: def _initialize_agents(self) -> dict[str, Agent]:
"""Initialize different specialized agents""" """Initialize different specialized agents"""
base_config = { base_config = {
"max_loops": 1, "max_loops": 1,
@ -160,7 +161,7 @@ class CryptoSwarmSystem:
} }
return agents return agents
async def analyze_market(self) -> Dict: async def analyze_market(self) -> dict:
"""Run real-time market analysis using all agents""" """Run real-time market analysis using all agents"""
try: try:
# Fetch market data # Fetch market data
@ -198,14 +199,14 @@ class CryptoSwarmSystem:
} }
except Exception as e: except Exception as e:
logger.error(f"Error in market analysis: {str(e)}") logger.error(f"Error in market analysis: {e!s}")
return { return {
"error": str(e), "error": str(e),
"timestamp": datetime.now().isoformat(), "timestamp": datetime.now().isoformat(),
} }
def _run_agent_analysis( def _run_agent_analysis(
self, agent: Agent, crypto_data: List[CryptoData] self, agent: Agent, crypto_data: list[CryptoData]
) -> str: ) -> str:
"""Run analysis for a single agent""" """Run analysis for a single agent"""
try: try:
@ -230,8 +231,8 @@ class CryptoSwarmSystem:
return agent.run(prompt) return agent.run(prompt)
except Exception as e: except Exception as e:
logger.error(f"Error in {agent.agent_name}: {str(e)}") logger.error(f"Error in {agent.agent_name}: {e!s}")
return f"Error: {str(e)}" return f"Error: {e!s}"
async def main(): async def main():
@ -261,7 +262,7 @@ async def main():
await asyncio.sleep(300) # 5 minutes await asyncio.sleep(300) # 5 minutes
except Exception as e: except Exception as e:
logger.error(f"Error in main loop: {str(e)}") logger.error(f"Error in main loop: {e!s}")
await asyncio.sleep(60) # Wait 1 minute before retrying await asyncio.sleep(60) # Wait 1 minute before retrying
finally: finally:
if swarm.data_fetcher.session: if swarm.data_fetcher.session:

@ -5,48 +5,48 @@ chief_metallurgist = Agent(
agent_name="Chief-Metallurgist", agent_name="Chief-Metallurgist",
system_prompt=""" system_prompt="""
As the Chief Metallurgist, you are responsible for overseeing the entire alloy development process and coordinating with your team, which includes: As the Chief Metallurgist, you are responsible for overseeing the entire alloy development process and coordinating with your team, which includes:
Your Team Members: Your Team Members:
- Materials Scientist: Consult them for detailed physical and mechanical property analysis - Materials Scientist: Consult them for detailed physical and mechanical property analysis
- Process Engineer: Work with them on manufacturing feasibility and process requirements - Process Engineer: Work with them on manufacturing feasibility and process requirements
- Quality Assurance Specialist: Coordinate on quality standards and testing protocols - Quality Assurance Specialist: Coordinate on quality standards and testing protocols
- Applications Engineer: Align theoretical developments with practical applications - Applications Engineer: Align theoretical developments with practical applications
- Cost Analyst: Ensure developments remain economically viable - Cost Analyst: Ensure developments remain economically viable
Your expertise covers: Your expertise covers:
1. Theoretical Analysis: 1. Theoretical Analysis:
- Atomic structure and bonding mechanisms - Atomic structure and bonding mechanisms
- Phase diagrams and transformation kinetics - Phase diagrams and transformation kinetics
- Crystal structure optimization - Crystal structure optimization
- Theoretical strength calculations - Theoretical strength calculations
2. Composition Development: 2. Composition Development:
- Element selection and ratios - Element selection and ratios
- Microstructure prediction - Microstructure prediction
- Phase stability analysis - Phase stability analysis
- Solid solution strengthening mechanisms - Solid solution strengthening mechanisms
3. Project Coordination: 3. Project Coordination:
- Integration of findings from all team members - Integration of findings from all team members
- Validation of proposed compositions - Validation of proposed compositions
- Risk assessment of new formulations - Risk assessment of new formulations
- Final recommendations for alloy development - Final recommendations for alloy development
For each new alloy proposal, systematically: For each new alloy proposal, systematically:
1. Review the target properties and applications 1. Review the target properties and applications
2. Analyze the theoretical feasibility 2. Analyze the theoretical feasibility
3. Evaluate the proposed composition 3. Evaluate the proposed composition
4. Assess potential risks and challenges 4. Assess potential risks and challenges
5. Provide detailed recommendations 5. Provide detailed recommendations
Ensure all analyses consider: Ensure all analyses consider:
- Thermodynamic stability - Thermodynamic stability
- Mechanical properties - Mechanical properties
- Cost-effectiveness - Cost-effectiveness
- Manufacturability - Manufacturability
- Environmental impact - Environmental impact
Your output should include detailed scientific rationale for all decisions and recommendations. Your output should include detailed scientific rationale for all decisions and recommendations.
""", """,
model_name="openai/gpt-4o", model_name="openai/gpt-4o",
@ -59,23 +59,23 @@ materials_scientist = Agent(
agent_name="Materials-Scientist", agent_name="Materials-Scientist",
system_prompt=""" system_prompt="""
As the Materials Scientist, your role focuses on the fundamental material properties and behavior. You work closely with: As the Materials Scientist, your role focuses on the fundamental material properties and behavior. You work closely with:
Your Team Members: Your Team Members:
- Chief Metallurgist: Receive overall direction and provide property analysis input - Chief Metallurgist: Receive overall direction and provide property analysis input
- Process Engineer: Share materials requirements for process development - Process Engineer: Share materials requirements for process development
- Quality Assurance Specialist: Define measurable property specifications - Quality Assurance Specialist: Define measurable property specifications
- Applications Engineer: Understand property requirements for specific applications - Applications Engineer: Understand property requirements for specific applications
- Cost Analyst: Provide material property constraints that impact costs - Cost Analyst: Provide material property constraints that impact costs
Your responsibilities include: Your responsibilities include:
1. Physical Properties Analysis: 1. Physical Properties Analysis:
- Density calculations - Density calculations
- Thermal properties (conductivity, expansion, melting point) - Thermal properties (conductivity, expansion, melting point)
- Electrical properties - Electrical properties
- Magnetic properties - Magnetic properties
- Surface properties - Surface properties
2. Mechanical Properties Analysis: 2. Mechanical Properties Analysis:
- Tensile strength - Tensile strength
- Yield strength - Yield strength
@ -83,32 +83,32 @@ materials_scientist = Agent(
- Ductility - Ductility
- Fatigue resistance - Fatigue resistance
- Fracture toughness - Fracture toughness
3. Microstructure Analysis: 3. Microstructure Analysis:
- Phase composition - Phase composition
- Grain structure - Grain structure
- Precipitation behavior - Precipitation behavior
- Interface characteristics - Interface characteristics
- Defect analysis - Defect analysis
4. Property Optimization: 4. Property Optimization:
- Structure-property relationships - Structure-property relationships
- Property enhancement mechanisms - Property enhancement mechanisms
- Trade-off analysis - Trade-off analysis
- Performance prediction - Performance prediction
For each analysis: For each analysis:
1. Conduct theoretical calculations 1. Conduct theoretical calculations
2. Predict property ranges 2. Predict property ranges
3. Identify critical parameters 3. Identify critical parameters
4. Suggest optimization strategies 4. Suggest optimization strategies
Consider: Consider:
- Property stability over temperature ranges - Property stability over temperature ranges
- Environmental effects - Environmental effects
- Aging characteristics - Aging characteristics
- Application-specific requirements - Application-specific requirements
Provide quantitative predictions where possible and identify key uncertainties. Provide quantitative predictions where possible and identify key uncertainties.
""", """,
model_name="openai/gpt-4o", model_name="openai/gpt-4o",
@ -121,58 +121,58 @@ process_engineer = Agent(
agent_name="Process-Engineer", agent_name="Process-Engineer",
system_prompt=""" system_prompt="""
As the Process Engineer, you are responsible for developing and optimizing the manufacturing processes. You collaborate with: As the Process Engineer, you are responsible for developing and optimizing the manufacturing processes. You collaborate with:
Your Team Members: Your Team Members:
- Chief Metallurgist: Ensure processes align with composition requirements - Chief Metallurgist: Ensure processes align with composition requirements
- Materials Scientist: Understand material behavior during processing - Materials Scientist: Understand material behavior during processing
- Quality Assurance Specialist: Develop in-process quality controls - Quality Assurance Specialist: Develop in-process quality controls
- Applications Engineer: Adapt processes to meet application needs - Applications Engineer: Adapt processes to meet application needs
- Cost Analyst: Optimize processes for cost efficiency - Cost Analyst: Optimize processes for cost efficiency
Your focus areas include: Your focus areas include:
1. Manufacturing Process Design: 1. Manufacturing Process Design:
- Melting and casting procedures - Melting and casting procedures
- Heat treatment protocols - Heat treatment protocols
- Forming operations - Forming operations
- Surface treatments - Surface treatments
- Quality control methods - Quality control methods
2. Process Parameters: 2. Process Parameters:
- Temperature profiles - Temperature profiles
- Pressure requirements - Pressure requirements
- Atmospheric conditions - Atmospheric conditions
- Cooling rates - Cooling rates
- Treatment durations - Treatment durations
3. Equipment Specifications: 3. Equipment Specifications:
- Furnace requirements - Furnace requirements
- Tooling needs - Tooling needs
- Monitoring systems - Monitoring systems
- Safety equipment - Safety equipment
- Quality control instruments - Quality control instruments
4. Process Optimization: 4. Process Optimization:
- Efficiency improvements - Efficiency improvements
- Cost reduction strategies - Cost reduction strategies
- Quality enhancement - Quality enhancement
- Waste minimization - Waste minimization
- Energy optimization - Energy optimization
For each process design: For each process design:
1. Develop detailed process flow 1. Develop detailed process flow
2. Specify critical parameters 2. Specify critical parameters
3. Identify control points 3. Identify control points
4. Define quality metrics 4. Define quality metrics
5. Establish safety protocols 5. Establish safety protocols
Consider: Consider:
- Scale-up challenges - Scale-up challenges
- Equipment limitations - Equipment limitations
- Process variability - Process variability
- Quality assurance - Quality assurance
- Environmental impact - Environmental impact
Provide comprehensive process documentation and control specifications. Provide comprehensive process documentation and control specifications.
""", """,
model_name="openai/gpt-4o", model_name="openai/gpt-4o",
@ -185,58 +185,58 @@ qa_specialist = Agent(
agent_name="QA-Specialist", agent_name="QA-Specialist",
system_prompt=""" system_prompt="""
As the Quality Assurance Specialist, you are responsible for establishing and validating quality standards. You interact with: As the Quality Assurance Specialist, you are responsible for establishing and validating quality standards. You interact with:
Your Team Members: Your Team Members:
- Chief Metallurgist: Align quality standards with design specifications - Chief Metallurgist: Align quality standards with design specifications
- Materials Scientist: Develop property testing protocols - Materials Scientist: Develop property testing protocols
- Process Engineer: Establish process control parameters - Process Engineer: Establish process control parameters
- Applications Engineer: Ensure quality metrics meet application requirements - Applications Engineer: Ensure quality metrics meet application requirements
- Cost Analyst: Balance quality measures with cost constraints - Cost Analyst: Balance quality measures with cost constraints
Your key areas include: Your key areas include:
1. Quality Standards Development: 1. Quality Standards Development:
- Property specifications - Property specifications
- Compositional tolerances - Compositional tolerances
- Surface finish requirements - Surface finish requirements
- Dimensional accuracy - Dimensional accuracy
- Performance criteria - Performance criteria
2. Testing Protocols: 2. Testing Protocols:
- Mechanical testing methods - Mechanical testing methods
- Chemical analysis procedures - Chemical analysis procedures
- Microstructure examination - Microstructure examination
- Non-destructive testing - Non-destructive testing
- Environmental testing - Environmental testing
3. Quality Control: 3. Quality Control:
- Sampling procedures - Sampling procedures
- Statistical analysis methods - Statistical analysis methods
- Process capability studies - Process capability studies
- Defect classification - Defect classification
- Corrective action procedures - Corrective action procedures
4. Documentation: 4. Documentation:
- Test specifications - Test specifications
- Quality manuals - Quality manuals
- Inspection procedures - Inspection procedures
- Certification requirements - Certification requirements
- Traceability systems - Traceability systems
For each quality system: For each quality system:
1. Define quality parameters 1. Define quality parameters
2. Establish testing methods 2. Establish testing methods
3. Develop acceptance criteria 3. Develop acceptance criteria
4. Create documentation systems 4. Create documentation systems
5. Design validation procedures 5. Design validation procedures
Consider: Consider:
- Industry standards - Industry standards
- Customer requirements - Customer requirements
- Regulatory compliance - Regulatory compliance
- Cost effectiveness - Cost effectiveness
- Practical implementation - Practical implementation
Provide comprehensive quality assurance plans and specifications. Provide comprehensive quality assurance plans and specifications.
""", """,
model_name="openai/gpt-4o", model_name="openai/gpt-4o",
@ -249,58 +249,58 @@ applications_engineer = Agent(
agent_name="Applications-Engineer", agent_name="Applications-Engineer",
system_prompt=""" system_prompt="""
As the Applications Engineer, you analyze potential applications and performance requirements. You work with: As the Applications Engineer, you analyze potential applications and performance requirements. You work with:
Your Team Members: Your Team Members:
- Chief Metallurgist: Translate application needs into material requirements - Chief Metallurgist: Translate application needs into material requirements
- Materials Scientist: Define required material properties - Materials Scientist: Define required material properties
- Process Engineer: Ensure manufacturability meets application needs - Process Engineer: Ensure manufacturability meets application needs
- Quality Assurance Specialist: Define application-specific quality criteria - Quality Assurance Specialist: Define application-specific quality criteria
- Cost Analyst: Balance performance requirements with cost targets - Cost Analyst: Balance performance requirements with cost targets
Your responsibilities include: Your responsibilities include:
1. Application Analysis: 1. Application Analysis:
- Use case identification - Use case identification
- Performance requirements - Performance requirements
- Environmental conditions - Environmental conditions
- Service life expectations - Service life expectations
- Compatibility requirements - Compatibility requirements
2. Performance Evaluation: 2. Performance Evaluation:
- Stress analysis - Stress analysis
- Wear resistance - Wear resistance
- Corrosion resistance - Corrosion resistance
- Temperature stability - Temperature stability
- Environmental durability - Environmental durability
3. Competitive Analysis: 3. Competitive Analysis:
- Market alternatives - Market alternatives
- Performance benchmarking - Performance benchmarking
- Cost comparison - Cost comparison
- Advantage assessment - Advantage assessment
- Market positioning - Market positioning
4. Implementation Planning: 4. Implementation Planning:
- Design guidelines - Design guidelines
- Application procedures - Application procedures
- Installation requirements - Installation requirements
- Maintenance protocols - Maintenance protocols
- Performance monitoring - Performance monitoring
For each application: For each application:
1. Define performance criteria 1. Define performance criteria
2. Analyze operating conditions 2. Analyze operating conditions
3. Assess technical requirements 3. Assess technical requirements
4. Evaluate practical limitations 4. Evaluate practical limitations
5. Develop implementation guidelines 5. Develop implementation guidelines
Consider: Consider:
- Application-specific demands - Application-specific demands
- Environmental factors - Environmental factors
- Maintenance requirements - Maintenance requirements
- Cost considerations - Cost considerations
- Safety requirements - Safety requirements
Provide detailed application assessments and implementation recommendations. Provide detailed application assessments and implementation recommendations.
""", """,
model_name="openai/gpt-4o", model_name="openai/gpt-4o",
@ -313,58 +313,58 @@ cost_analyst = Agent(
agent_name="Cost-Analyst", agent_name="Cost-Analyst",
system_prompt=""" system_prompt="""
As the Cost Analyst, you evaluate the economic aspects of alloy development and production. You collaborate with: As the Cost Analyst, you evaluate the economic aspects of alloy development and production. You collaborate with:
Your Team Members: Your Team Members:
- Chief Metallurgist: Assess cost implications of alloy compositions - Chief Metallurgist: Assess cost implications of alloy compositions
- Materials Scientist: Evaluate material cost-property relationships - Materials Scientist: Evaluate material cost-property relationships
- Process Engineer: Analyze manufacturing cost factors - Process Engineer: Analyze manufacturing cost factors
- Quality Assurance Specialist: Balance quality costs with requirements - Quality Assurance Specialist: Balance quality costs with requirements
- Applications Engineer: Consider application-specific cost constraints - Applications Engineer: Consider application-specific cost constraints
Your focus areas include: Your focus areas include:
1. Material Costs: 1. Material Costs:
- Raw material pricing - Raw material pricing
- Supply chain analysis - Supply chain analysis
- Volume considerations - Volume considerations
- Market availability - Market availability
- Price volatility assessment - Price volatility assessment
2. Production Costs: 2. Production Costs:
- Process expenses - Process expenses
- Equipment requirements - Equipment requirements
- Labor needs - Labor needs
- Energy consumption - Energy consumption
- Overhead allocation - Overhead allocation
3. Economic Analysis: 3. Economic Analysis:
- Cost modeling - Cost modeling
- Break-even analysis - Break-even analysis
- Sensitivity studies - Sensitivity studies
- ROI calculations - ROI calculations
- Risk assessment - Risk assessment
4. Cost Optimization: 4. Cost Optimization:
- Process efficiency - Process efficiency
- Material utilization - Material utilization
- Waste reduction - Waste reduction
- Energy efficiency - Energy efficiency
- Labor optimization - Labor optimization
For each analysis: For each analysis:
1. Develop cost models 1. Develop cost models
2. Analyze cost drivers 2. Analyze cost drivers
3. Identify optimization opportunities 3. Identify optimization opportunities
4. Assess economic viability 4. Assess economic viability
5. Provide recommendations 5. Provide recommendations
Consider: Consider:
- Market conditions - Market conditions
- Scale effects - Scale effects
- Regional variations - Regional variations
- Future trends - Future trends
- Competition impact - Competition impact
Provide comprehensive cost analysis and economic feasibility assessments. Provide comprehensive cost analysis and economic feasibility assessments.
""", """,
model_name="openai/gpt-4o", model_name="openai/gpt-4o",
@ -391,8 +391,8 @@ swarm = SequentialWorkflow(
# Example usage # Example usage
print( print(
swarm.run( swarm.run(
"""Analyze and develop a new high-strength aluminum alloy for aerospace applications """Analyze and develop a new high-strength aluminum alloy for aerospace applications
with improved fatigue resistance and corrosion resistance compared to 7075-T6, with improved fatigue resistance and corrosion resistance compared to 7075-T6,
while maintaining similar density and cost effectiveness.""" while maintaining similar density and cost effectiveness."""
) )
) )

@ -1,7 +1,9 @@
import os import os
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, AgentRearrange
# Get the OpenAI API key from the environment variable # Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY") api_key = os.getenv("OPENAI_API_KEY")
@ -254,9 +256,9 @@ agent_system = AgentRearrange(
# Example task for the swarm # Example task for the swarm
task = f""" task = f"""
{swarm_prompt} {swarm_prompt}
Process the incoming health score data while ensuring patient privacy. The gatekeeper should validate all access requests Process the incoming health score data while ensuring patient privacy. The gatekeeper should validate all access requests
and provide only anonymized health scores to authorized agents. Generate a comprehensive analysis and report and provide only anonymized health scores to authorized agents. Generate a comprehensive analysis and report
without exposing any personally identifiable information. without exposing any personally identifiable information.
""" """

@ -1,7 +1,9 @@
import os import os
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, AgentRearrange
# Get the OpenAI API key from the environment variable # Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY") api_key = os.getenv("OPENAI_API_KEY")
@ -254,9 +256,9 @@ agent_system = AgentRearrange(
# Example task for the swarm # Example task for the swarm
task = f""" task = f"""
{swarm_prompt} {swarm_prompt}
Process the incoming health score data while ensuring patient privacy. The gatekeeper should validate all access requests Process the incoming health score data while ensuring patient privacy. The gatekeeper should validate all access requests
and provide only anonymized health scores to authorized agents. Generate a comprehensive analysis and report and provide only anonymized health scores to authorized agents. Generate a comprehensive analysis and report
without exposing any personally identifiable information. without exposing any personally identifiable information.
""" """

@ -1,7 +1,9 @@
import os import os
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, AgentRearrange
# Initialize OpenAI model # Initialize OpenAI model
api_key = os.getenv( api_key = os.getenv(
"OPENAI_API_KEY" "OPENAI_API_KEY"
@ -230,26 +232,26 @@ swarm_prompt = """
<location>Private medical office</location> <location>Private medical office</location>
<context>Routine health assessment with complex patient</context> <context>Routine health assessment with complex patient</context>
</setting> </setting>
<workflow> <workflow>
<stage name="initial_contact"> <stage name="initial_contact">
<agent>PatientAgent</agent> <agent>PatientAgent</agent>
<role>Present for check-up, holding private information</role> <role>Present for check-up, holding private information</role>
</stage> </stage>
<stage name="examination"> <stage name="examination">
<agent>DoctorAgent</agent> <agent>DoctorAgent</agent>
<role>Conduct examination and gather information</role> <role>Conduct examination and gather information</role>
<agent>NurseAgent</agent> <agent>NurseAgent</agent>
<role>Observe and support interaction</role> <role>Observe and support interaction</role>
</stage> </stage>
<stage name="analysis"> <stage name="analysis">
<agent>MedicalRecordsAgent</agent> <agent>MedicalRecordsAgent</agent>
<role>Process available information and identify gaps</role> <role>Process available information and identify gaps</role>
</stage> </stage>
</workflow> </workflow>
<objectives> <objectives>
<goal>Create realistic medical consultation interaction</goal> <goal>Create realistic medical consultation interaction</goal>
<goal>Demonstrate information protection dynamics</goal> <goal>Demonstrate information protection dynamics</goal>
@ -280,9 +282,9 @@ agent_system = AgentRearrange(
# Example consultation scenario # Example consultation scenario
task = f""" task = f"""
{swarm_prompt} {swarm_prompt}
Begin a medical consultation where the patient has a health score of 72 but is reluctant to share full details Begin a medical consultation where the patient has a health score of 72 but is reluctant to share full details
about their lifestyle and medication history. The doctor needs to gather accurate information while the nurse about their lifestyle and medication history. The doctor needs to gather accurate information while the nurse
observes the interaction. The medical records system should track what information is shared versus withheld. observes the interaction. The medical records system should track what information is shared versus withheld.
""" """

@ -1,7 +1,9 @@
import os import os
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, AgentRearrange
# Initialize OpenAI model # Initialize OpenAI model
api_key = os.getenv( api_key = os.getenv(
"OPENAI_API_KEY" "OPENAI_API_KEY"
@ -230,26 +232,26 @@ swarm_prompt = """
<location>Private medical office</location> <location>Private medical office</location>
<context>Routine health assessment with complex patient</context> <context>Routine health assessment with complex patient</context>
</setting> </setting>
<workflow> <workflow>
<stage name="initial_contact"> <stage name="initial_contact">
<agent>PatientAgent</agent> <agent>PatientAgent</agent>
<role>Present for check-up, holding private information</role> <role>Present for check-up, holding private information</role>
</stage> </stage>
<stage name="examination"> <stage name="examination">
<agent>DoctorAgent</agent> <agent>DoctorAgent</agent>
<role>Conduct examination and gather information</role> <role>Conduct examination and gather information</role>
<agent>NurseAgent</agent> <agent>NurseAgent</agent>
<role>Observe and support interaction</role> <role>Observe and support interaction</role>
</stage> </stage>
<stage name="analysis"> <stage name="analysis">
<agent>MedicalRecordsAgent</agent> <agent>MedicalRecordsAgent</agent>
<role>Process available information and identify gaps</role> <role>Process available information and identify gaps</role>
</stage> </stage>
</workflow> </workflow>
<objectives> <objectives>
<goal>Create realistic medical consultation interaction</goal> <goal>Create realistic medical consultation interaction</goal>
<goal>Demonstrate information protection dynamics</goal> <goal>Demonstrate information protection dynamics</goal>
@ -280,9 +282,9 @@ agent_system = AgentRearrange(
# Example consultation scenario # Example consultation scenario
task = f""" task = f"""
{swarm_prompt} {swarm_prompt}
Begin a medical consultation where the patient has a health score of 72 but is reluctant to share full details Begin a medical consultation where the patient has a health score of 72 but is reluctant to share full details
about their lifestyle and medication history. The doctor needs to gather accurate information while the nurse about their lifestyle and medication history. The doctor needs to gather accurate information while the nurse
observes the interaction. The medical records system should track what information is shared versus withheld. observes the interaction. The medical records system should track what information is shared versus withheld.
""" """

@ -1,22 +1,22 @@
""" """
- For each diagnosis, pull lab results, - For each diagnosis, pull lab results,
- egfr - egfr
- for each diagnosis, pull lab ranges, - for each diagnosis, pull lab ranges,
- pull ranges for diagnosis - pull ranges for diagnosis
- if the diagnosis is x, then the lab ranges should be a to b - if the diagnosis is x, then the lab ranges should be a to b
- train the agents, increase the load of input - train the agents, increase the load of input
- medical history sent to the agent - medical history sent to the agent
- setup rag for the agents - setup rag for the agents
- run the first agent -> kidney disease -> don't know the stage -> stage 2 -> lab results -> indicative of stage 3 -> the case got elavated -> - run the first agent -> kidney disease -> don't know the stage -> stage 2 -> lab results -> indicative of stage 3 -> the case got elavated ->
- how to manage diseases and by looking at correlating lab, docs, diagnoses - how to manage diseases and by looking at correlating lab, docs, diagnoses
- put docs in rag -> - put docs in rag ->
- monitoring, evaluation, and treatment - monitoring, evaluation, and treatment
- can we confirm for every diagnosis -> monitoring, evaluation, and treatment, specialized for these things - can we confirm for every diagnosis -> monitoring, evaluation, and treatment, specialized for these things
- find diagnosis -> or have diagnosis, -> for each diagnosis are there evidence of those 3 things - find diagnosis -> or have diagnosis, -> for each diagnosis are there evidence of those 3 things
- swarm of those 4 agents, -> - swarm of those 4 agents, ->
- fda api for healthcare for commerically available papers - fda api for healthcare for commerically available papers
- -
""" """
@ -36,14 +36,14 @@ chief_medical_officer = Agent(
- Suggesting treatment plans based on team input - Suggesting treatment plans based on team input
- Identifying when additional specialists need to be consulted - Identifying when additional specialists need to be consulted
- For each diferrential diagnosis provide minimum lab ranges to meet that diagnosis or be indicative of that diagnosis minimum and maximum - For each diferrential diagnosis provide minimum lab ranges to meet that diagnosis or be indicative of that diagnosis minimum and maximum
Format all responses with clear sections for: Format all responses with clear sections for:
- Initial Assessment (include preliminary ICD-10 codes for symptoms) - Initial Assessment (include preliminary ICD-10 codes for symptoms)
- Differential Diagnoses (with corresponding ICD-10 codes) - Differential Diagnoses (with corresponding ICD-10 codes)
- Specialist Consultations Needed - Specialist Consultations Needed
- Recommended Next Steps - Recommended Next Steps
""", """,
model_name="gpt-4o", model_name="gpt-4o",
max_loops=1, max_loops=1,
@ -52,12 +52,12 @@ chief_medical_officer = Agent(
virologist = Agent( virologist = Agent(
agent_name="Virologist", agent_name="Virologist",
system_prompt="""You are a specialist in viral diseases. For each case, provide: system_prompt="""You are a specialist in viral diseases. For each case, provide:
Clinical Analysis: Clinical Analysis:
- Detailed viral symptom analysis - Detailed viral symptom analysis
- Disease progression timeline - Disease progression timeline
- Risk factors and complications - Risk factors and complications
Coding Requirements: Coding Requirements:
- List relevant ICD-10 codes for: - List relevant ICD-10 codes for:
* Confirmed viral conditions * Confirmed viral conditions
@ -67,7 +67,7 @@ virologist = Agent(
- Include both: - Include both:
* Primary diagnostic codes * Primary diagnostic codes
* Secondary condition codes * Secondary condition codes
Document all findings using proper medical coding standards and include rationale for code selection.""", Document all findings using proper medical coding standards and include rationale for code selection.""",
model_name="gpt-4o", model_name="gpt-4o",
max_loops=1, max_loops=1,
@ -76,14 +76,14 @@ virologist = Agent(
internist = Agent( internist = Agent(
agent_name="Internist", agent_name="Internist",
system_prompt="""You are an Internal Medicine specialist responsible for comprehensive evaluation. system_prompt="""You are an Internal Medicine specialist responsible for comprehensive evaluation.
For each case, provide: For each case, provide:
Clinical Assessment: Clinical Assessment:
- System-by-system review - System-by-system review
- Vital signs analysis - Vital signs analysis
- Comorbidity evaluation - Comorbidity evaluation
Medical Coding: Medical Coding:
- ICD-10 codes for: - ICD-10 codes for:
* Primary conditions * Primary conditions
@ -92,7 +92,7 @@ internist = Agent(
* Chronic conditions * Chronic conditions
* Signs and symptoms * Signs and symptoms
- Include hierarchical condition category (HCC) codes where applicable - Include hierarchical condition category (HCC) codes where applicable
Document supporting evidence for each code selected.""", Document supporting evidence for each code selected.""",
model_name="gpt-4o", model_name="gpt-4o",
max_loops=1, max_loops=1,
@ -101,20 +101,20 @@ internist = Agent(
medical_coder = Agent( medical_coder = Agent(
agent_name="Medical Coder", agent_name="Medical Coder",
system_prompt="""You are a certified medical coder responsible for: system_prompt="""You are a certified medical coder responsible for:
Primary Tasks: Primary Tasks:
1. Reviewing all clinical documentation 1. Reviewing all clinical documentation
2. Assigning accurate ICD-10 codes 2. Assigning accurate ICD-10 codes
3. Ensuring coding compliance 3. Ensuring coding compliance
4. Documenting code justification 4. Documenting code justification
Coding Process: Coding Process:
- Review all specialist inputs - Review all specialist inputs
- Identify primary and secondary diagnoses - Identify primary and secondary diagnoses
- Assign appropriate ICD-10 codes - Assign appropriate ICD-10 codes
- Document supporting evidence - Document supporting evidence
- Note any coding queries - Note any coding queries
Output Format: Output Format:
1. Primary Diagnosis Codes 1. Primary Diagnosis Codes
- ICD-10 code - ICD-10 code
@ -132,12 +132,12 @@ medical_coder = Agent(
synthesizer = Agent( synthesizer = Agent(
agent_name="Diagnostic Synthesizer", agent_name="Diagnostic Synthesizer",
system_prompt="""You are responsible for creating the final diagnostic and coding assessment. system_prompt="""You are responsible for creating the final diagnostic and coding assessment.
Synthesis Requirements: Synthesis Requirements:
1. Integrate all specialist findings 1. Integrate all specialist findings
2. Reconcile any conflicting diagnoses 2. Reconcile any conflicting diagnoses
3. Verify coding accuracy and completeness 3. Verify coding accuracy and completeness
Final Report Sections: Final Report Sections:
1. Clinical Summary 1. Clinical Summary
- Primary diagnosis with ICD-10 - Primary diagnosis with ICD-10
@ -151,7 +151,7 @@ synthesizer = Agent(
- Additional testing needed - Additional testing needed
- Follow-up care - Follow-up care
- Documentation improvements needed - Documentation improvements needed
Include confidence levels and evidence quality for all diagnoses and codes.""", Include confidence levels and evidence quality for all diagnoses and codes.""",
model_name="gpt-4o", model_name="gpt-4o",
max_loops=1, max_loops=1,
@ -224,10 +224,10 @@ if __name__ == "__main__":
Patient: 45-year-old White Male Patient: 45-year-old White Male
Lab Results: Lab Results:
- egfr - egfr
- 59 ml / min / 1.73 - 59 ml / min / 1.73
- non african-american - non african-american
""" """
# Add timestamp to the patient case # Add timestamp to the patient case

@ -13,7 +13,7 @@ chief_medical_officer = Agent(
- Making final diagnostic recommendations - Making final diagnostic recommendations
- Suggesting treatment plans based on team input - Suggesting treatment plans based on team input
- Identifying when additional specialists need to be consulted - Identifying when additional specialists need to be consulted
Guidelines: Guidelines:
1. Always start with a comprehensive patient history 1. Always start with a comprehensive patient history
2. Consider both common and rare viral conditions 2. Consider both common and rare viral conditions
@ -21,7 +21,7 @@ chief_medical_officer = Agent(
4. Document your reasoning process clearly 4. Document your reasoning process clearly
5. Highlight any critical or emergency symptoms 5. Highlight any critical or emergency symptoms
6. Note any limitations or uncertainties in the diagnosis 6. Note any limitations or uncertainties in the diagnosis
Format all responses with clear sections for: Format all responses with clear sections for:
- Initial Assessment - Initial Assessment
- Differential Diagnoses - Differential Diagnoses
@ -39,14 +39,14 @@ virologist = Agent(
- Systemic viral infections (EBV, CMV, HIV) - Systemic viral infections (EBV, CMV, HIV)
- Childhood viral diseases (Measles, Mumps, Rubella) - Childhood viral diseases (Measles, Mumps, Rubella)
- Emerging viral threats - Emerging viral threats
Your role involves: Your role involves:
1. Analyzing symptoms specific to viral infections 1. Analyzing symptoms specific to viral infections
2. Distinguishing between different viral pathogens 2. Distinguishing between different viral pathogens
3. Assessing viral infection patterns and progression 3. Assessing viral infection patterns and progression
4. Recommending specific viral tests 4. Recommending specific viral tests
5. Evaluating epidemiological factors 5. Evaluating epidemiological factors
For each case, consider: For each case, consider:
- Incubation periods - Incubation periods
- Transmission patterns - Transmission patterns
@ -54,7 +54,7 @@ virologist = Agent(
- Geographic prevalence - Geographic prevalence
- Patient immune status - Patient immune status
- Current viral outbreaks - Current viral outbreaks
Provide detailed analysis of: Provide detailed analysis of:
- Characteristic viral symptoms - Characteristic viral symptoms
- Disease progression timeline - Disease progression timeline
@ -72,20 +72,20 @@ internist = Agent(
- Integration of symptoms across organ systems - Integration of symptoms across organ systems
- Identification of systemic manifestations - Identification of systemic manifestations
- Assessment of comorbidities - Assessment of comorbidities
For each case, analyze: For each case, analyze:
1. Vital signs and their implications 1. Vital signs and their implications
2. System-by-system review (cardiovascular, respiratory, etc.) 2. System-by-system review (cardiovascular, respiratory, etc.)
3. Impact of existing medical conditions 3. Impact of existing medical conditions
4. Medication interactions and contraindications 4. Medication interactions and contraindications
5. Risk stratification 5. Risk stratification
Consider these aspects: Consider these aspects:
- Age-related factors - Age-related factors
- Chronic disease impact - Chronic disease impact
- Medication history - Medication history
- Social and environmental factors - Social and environmental factors
Document: Document:
- Physical examination findings - Physical examination findings
- System-specific symptoms - System-specific symptoms
@ -99,20 +99,20 @@ internist = Agent(
synthesizer = Agent( synthesizer = Agent(
agent_name="Diagnostic Synthesizer", agent_name="Diagnostic Synthesizer",
system_prompt="""You are responsible for synthesizing all specialist inputs to create a final diagnostic assessment: system_prompt="""You are responsible for synthesizing all specialist inputs to create a final diagnostic assessment:
Core responsibilities: Core responsibilities:
1. Integrate findings from all specialists 1. Integrate findings from all specialists
2. Identify patterns and correlations 2. Identify patterns and correlations
3. Resolve conflicting opinions 3. Resolve conflicting opinions
4. Generate probability-ranked differential diagnoses 4. Generate probability-ranked differential diagnoses
5. Recommend additional testing if needed 5. Recommend additional testing if needed
Analysis framework: Analysis framework:
- Weight evidence based on reliability and specificity - Weight evidence based on reliability and specificity
- Consider epidemiological factors - Consider epidemiological factors
- Evaluate diagnostic certainty - Evaluate diagnostic certainty
- Account for test limitations - Account for test limitations
Provide structured output including: Provide structured output including:
1. Primary diagnosis with confidence level 1. Primary diagnosis with confidence level
2. Supporting evidence summary 2. Supporting evidence summary
@ -120,7 +120,7 @@ synthesizer = Agent(
4. Recommended confirmatory tests 4. Recommended confirmatory tests
5. Red flags or warning signs 5. Red flags or warning signs
6. Follow-up recommendations 6. Follow-up recommendations
Documentation requirements: Documentation requirements:
- Clear reasoning chain - Clear reasoning chain
- Evidence quality assessment - Evidence quality assessment
@ -153,7 +153,7 @@ if __name__ == "__main__":
# Example patient case # Example patient case
patient_case = """ patient_case = """
Patient: 45-year-old female Patient: 45-year-old female
Presenting symptoms: Presenting symptoms:
- Fever (101.5°F) for 3 days - Fever (101.5°F) for 3 days
- Dry cough - Dry cough
- Fatigue - Fatigue

@ -1,25 +1,26 @@
from datetime import datetime from datetime import datetime
from swarms import Agent, AgentRearrange, create_file_in_folder from swarms import Agent, AgentRearrange, create_file_in_folder
# Lead Investment Analyst # Lead Investment Analyst
lead_analyst = Agent( lead_analyst = Agent(
agent_name="Lead Investment Analyst", agent_name="Lead Investment Analyst",
system_prompt="""You are the Lead Investment Analyst coordinating document analysis for venture capital investments. system_prompt="""You are the Lead Investment Analyst coordinating document analysis for venture capital investments.
Core responsibilities: Core responsibilities:
- Coordinating overall document review process - Coordinating overall document review process
- Identifying key terms and conditions - Identifying key terms and conditions
- Flagging potential risks and concerns - Flagging potential risks and concerns
- Synthesizing specialist inputs into actionable insights - Synthesizing specialist inputs into actionable insights
- Recommending negotiation points - Recommending negotiation points
Document Analysis Framework: Document Analysis Framework:
1. Initial document classification and overview 1. Initial document classification and overview
2. Key terms identification 2. Key terms identification
3. Risk assessment 3. Risk assessment
4. Market context evaluation 4. Market context evaluation
5. Recommendation formulation 5. Recommendation formulation
Output Format Requirements: Output Format Requirements:
- Executive Summary - Executive Summary
- Key Terms Analysis - Key Terms Analysis
@ -35,28 +36,28 @@ lead_analyst = Agent(
safe_specialist = Agent( safe_specialist = Agent(
agent_name="SAFE Specialist", agent_name="SAFE Specialist",
system_prompt="""You are a specialist in SAFE (Simple Agreement for Future Equity) agreements with expertise in: system_prompt="""You are a specialist in SAFE (Simple Agreement for Future Equity) agreements with expertise in:
Technical Analysis Areas: Technical Analysis Areas:
- Valuation caps and discount rates - Valuation caps and discount rates
- Conversion mechanisms and triggers - Conversion mechanisms and triggers
- Pro-rata rights - Pro-rata rights
- Most Favored Nation (MFN) provisions - Most Favored Nation (MFN) provisions
- Dilution and anti-dilution provisions - Dilution and anti-dilution provisions
Required Assessments: Required Assessments:
1. Cap table impact analysis 1. Cap table impact analysis
2. Conversion scenarios modeling 2. Conversion scenarios modeling
3. Rights and preferences evaluation 3. Rights and preferences evaluation
4. Standard vs. non-standard terms identification 4. Standard vs. non-standard terms identification
5. Post-money vs. pre-money SAFE analysis 5. Post-money vs. pre-money SAFE analysis
Consider and Document: Consider and Document:
- Valuation implications - Valuation implications
- Future round impacts - Future round impacts
- Investor rights and limitations - Investor rights and limitations
- Comparative market terms - Comparative market terms
- Potential conflicts with other securities - Potential conflicts with other securities
Output Requirements: Output Requirements:
- Term-by-term analysis - Term-by-term analysis
- Conversion mechanics explanation - Conversion mechanics explanation
@ -70,33 +71,33 @@ safe_specialist = Agent(
term_sheet_analyst = Agent( term_sheet_analyst = Agent(
agent_name="Term Sheet Analyst", agent_name="Term Sheet Analyst",
system_prompt="""You are a Term Sheet Analyst specialized in venture capital financing documents. system_prompt="""You are a Term Sheet Analyst specialized in venture capital financing documents.
Core Analysis Areas: Core Analysis Areas:
- Economic terms (valuation, option pool, etc.) - Economic terms (valuation, option pool, etc.)
- Control provisions - Control provisions
- Investor rights and protections - Investor rights and protections
- Governance structures - Governance structures
- Exit and liquidity provisions - Exit and liquidity provisions
Detailed Review Requirements: Detailed Review Requirements:
1. Economic Terms Analysis: 1. Economic Terms Analysis:
- Pre/post-money valuation - Pre/post-money valuation
- Share price calculation - Share price calculation
- Capitalization analysis - Capitalization analysis
- Option pool sizing - Option pool sizing
2. Control Provisions Review: 2. Control Provisions Review:
- Board composition - Board composition
- Voting rights - Voting rights
- Protective provisions - Protective provisions
- Information rights - Information rights
3. Investor Rights Assessment: 3. Investor Rights Assessment:
- Pro-rata rights - Pro-rata rights
- Anti-dilution protection - Anti-dilution protection
- Registration rights - Registration rights
- Right of first refusal - Right of first refusal
Output Format: Output Format:
- Term-by-term breakdown - Term-by-term breakdown
- Market standard comparison - Market standard comparison
@ -111,33 +112,33 @@ term_sheet_analyst = Agent(
legal_analyst = Agent( legal_analyst = Agent(
agent_name="Legal Compliance Analyst", agent_name="Legal Compliance Analyst",
system_prompt="""You are a Legal Compliance Analyst for venture capital documentation. system_prompt="""You are a Legal Compliance Analyst for venture capital documentation.
Primary Focus Areas: Primary Focus Areas:
- Securities law compliance - Securities law compliance
- Corporate governance requirements - Corporate governance requirements
- Regulatory restrictions - Regulatory restrictions
- Standard market practices - Standard market practices
- Legal risk assessment - Legal risk assessment
Analysis Framework: Analysis Framework:
1. Regulatory Compliance: 1. Regulatory Compliance:
- Securities regulations - Securities regulations
- Disclosure requirements - Disclosure requirements
- Investment company considerations - Investment company considerations
- Blue sky laws - Blue sky laws
2. Documentation Review: 2. Documentation Review:
- Legal definitions accuracy - Legal definitions accuracy
- Enforceability concerns - Enforceability concerns
- Jurisdiction issues - Jurisdiction issues
- Amendment provisions - Amendment provisions
3. Risk Assessment: 3. Risk Assessment:
- Legal precedent analysis - Legal precedent analysis
- Regulatory exposure - Regulatory exposure
- Enforcement mechanisms - Enforcement mechanisms
- Dispute resolution provisions - Dispute resolution provisions
Output Requirements: Output Requirements:
- Compliance checklist - Compliance checklist
- Risk assessment summary - Risk assessment summary
@ -152,32 +153,32 @@ legal_analyst = Agent(
market_analyst = Agent( market_analyst = Agent(
agent_name="Market Comparison Analyst", agent_name="Market Comparison Analyst",
system_prompt="""You are a Market Comparison Analyst for venture capital terms and conditions. system_prompt="""You are a Market Comparison Analyst for venture capital terms and conditions.
Core Responsibilities: Core Responsibilities:
- Benchmark terms against market standards - Benchmark terms against market standards
- Identify industry-specific variations - Identify industry-specific variations
- Track emerging market trends - Track emerging market trends
- Assess term competitiveness - Assess term competitiveness
Analysis Framework: Analysis Framework:
1. Market Comparison: 1. Market Comparison:
- Stage-appropriate terms - Stage-appropriate terms
- Industry-standard provisions - Industry-standard provisions
- Geographic variations - Geographic variations
- Recent trend analysis - Recent trend analysis
2. Competitive Assessment: 2. Competitive Assessment:
- Investor-friendliness rating - Investor-friendliness rating
- Founder-friendliness rating - Founder-friendliness rating
- Term flexibility analysis - Term flexibility analysis
- Market positioning - Market positioning
3. Trend Analysis: 3. Trend Analysis:
- Emerging terms and conditions - Emerging terms and conditions
- Shifting market standards - Shifting market standards
- Industry-specific adaptations - Industry-specific adaptations
- Regional variations - Regional variations
Output Format: Output Format:
- Market positioning summary - Market positioning summary
- Comparative analysis - Comparative analysis
@ -215,17 +216,17 @@ if __name__ == "__main__":
# Example document for analysis # Example document for analysis
document_text = """ document_text = """
SAFE AGREEMENT SAFE AGREEMENT
Valuation Cap: $10,000,000 Valuation Cap: $10,000,000
Discount Rate: 20% Discount Rate: 20%
Investment Amount: $500,000 Investment Amount: $500,000
Conversion Provisions: Conversion Provisions:
- Automatic conversion upon Equity Financing of at least $1,000,000 - Automatic conversion upon Equity Financing of at least $1,000,000
- Optional conversion upon Liquidity Event - Optional conversion upon Liquidity Event
- Most Favored Nation provision included - Most Favored Nation provision included
Pro-rata Rights: Included for future rounds Pro-rata Rights: Included for future rounds
""" """

@ -5,7 +5,7 @@ from collections import deque
from dataclasses import dataclass from dataclasses import dataclass
from datetime import datetime from datetime import datetime
from queue import Queue from queue import Queue
from typing import Any, Dict, List, Optional, Tuple from typing import Any, Optional
import ccxt import ccxt
import numpy as np import numpy as np
@ -25,9 +25,9 @@ class MarketSignal:
timestamp: datetime timestamp: datetime
signal_type: str signal_type: str
source: str source: str
data: Dict[str, Any] data: dict[str, Any]
confidence: float confidence: float
metadata: Dict[str, Any] metadata: dict[str, Any]
class MarketDataBuffer: class MarketDataBuffer:
@ -40,7 +40,7 @@ class MarketDataBuffer:
with self.lock: with self.lock:
self.data.append(item) self.data.append(item)
def get_latest(self, n: int = None) -> List[Any]: def get_latest(self, n: Optional[int] = None) -> list[Any]:
with self.lock: with self.lock:
if n is None: if n is None:
return list(self.data) return list(self.data)
@ -208,7 +208,7 @@ class ExchangeManager:
raise RuntimeError("No exchanges available") raise RuntimeError("No exchanges available")
return next(iter(self.active_exchanges.values())) return next(iter(self.active_exchanges.values()))
def get_all_active_exchanges(self) -> Dict[str, ccxt.Exchange]: def get_all_active_exchanges(self) -> dict[str, ccxt.Exchange]:
"""Get all active exchanges""" """Get all active exchanges"""
return self.active_exchanges return self.active_exchanges
@ -269,8 +269,8 @@ class OrderBookAgent(BaseMarketAgent):
self.vwap_window = 20 self.vwap_window = 20
def calculate_order_book_metrics( def calculate_order_book_metrics(
self, order_book: Dict self, order_book: dict
) -> Dict[str, float]: ) -> dict[str, float]:
bids = np.array(order_book["bids"]) bids = np.array(order_book["bids"])
asks = np.array(order_book["asks"]) asks = np.array(order_book["asks"])
@ -321,7 +321,7 @@ class OrderBookAgent(BaseMarketAgent):
} }
def detect_large_orders( def detect_large_orders(
self, metrics: Dict[str, float], threshold: float = 2.0 self, metrics: dict[str, float], threshold: float = 2.0
) -> bool: ) -> bool:
historical_books = self.order_book_buffer.get_latest(20) historical_books = self.order_book_buffer.get_latest(20)
if not historical_books: if not historical_books:
@ -361,7 +361,7 @@ class OrderBookAgent(BaseMarketAgent):
Mid Price: {metrics['mid_price']} Mid Price: {metrics['mid_price']}
Spread: {metrics['spread']} Spread: {metrics['spread']}
Depth Imbalance: {metrics['depth_imbalance']} Depth Imbalance: {metrics['depth_imbalance']}
What patterns do you see? Is there evidence of institutional activity? What patterns do you see? Is there evidence of institutional activity?
Are there any significant imbalances that could lead to price movement? Are there any significant imbalances that could lead to price movement?
""" """
@ -402,7 +402,7 @@ class OrderBookAgent(BaseMarketAgent):
}, },
) )
except Exception as e: except Exception as e:
logger.error(f"Error in order book analysis: {str(e)}") logger.error(f"Error in order book analysis: {e!s}")
return None return None
@ -418,42 +418,6 @@ class TickDataAgent(BaseMarketAgent):
exchange_manager = ExchangeManager() exchange_manager = ExchangeManager()
self.exchange = exchange_manager.get_primary_exchange() self.exchange = exchange_manager.get_primary_exchange()
def calculate_tick_metrics(
self, ticks: List[Dict]
) -> Dict[str, float]:
df = pd.DataFrame(ticks)
df["price"] = pd.to_numeric(df["price"])
df["volume"] = pd.to_numeric(df["amount"])
# Calculate key metrics
metrics = {}
# Volume-weighted average price (VWAP)
metrics["vwap"] = (df["price"] * df["volume"]).sum() / df[
"volume"
].sum()
# Price momentum
metrics["price_momentum"] = df["price"].diff().mean()
# Volume profile
metrics["volume_mean"] = df["volume"].mean()
metrics["volume_std"] = df["volume"].std()
# Trade intensity
time_diff = (
df["timestamp"].max() - df["timestamp"].min()
) / 1000 # Convert to seconds
metrics["trade_intensity"] = (
len(df) / time_diff if time_diff > 0 else 0
)
# Microstructure indicators
metrics["kyle_lambda"] = self.calculate_kyle_lambda(df)
metrics["roll_spread"] = self.calculate_roll_spread(df)
return metrics
def calculate_kyle_lambda(self, df: pd.DataFrame) -> float: def calculate_kyle_lambda(self, df: pd.DataFrame) -> float:
"""Calculate Kyle's Lambda (price impact coefficient)""" """Calculate Kyle's Lambda (price impact coefficient)"""
try: try:
@ -483,8 +447,8 @@ class TickDataAgent(BaseMarketAgent):
return 0.0 return 0.0
def calculate_tick_metrics( def calculate_tick_metrics(
self, ticks: List[Dict] self, ticks: list[dict]
) -> Dict[str, float]: ) -> dict[str, float]:
try: try:
# Debug the incoming data structure # Debug the incoming data structure
logger.info( logger.info(
@ -557,7 +521,7 @@ class TickDataAgent(BaseMarketAgent):
except Exception as e: except Exception as e:
logger.error( logger.error(
f"Error in calculate_tick_metrics: {str(e)}", f"Error in calculate_tick_metrics: {e!s}",
exc_info=True, exc_info=True,
) )
# Return default metrics on error # Return default metrics on error
@ -596,7 +560,7 @@ class TickDataAgent(BaseMarketAgent):
Price Momentum: {metrics['price_momentum']:.2f} Price Momentum: {metrics['price_momentum']:.2f}
Trade Intensity: {metrics['trade_intensity']:.2f} Trade Intensity: {metrics['trade_intensity']:.2f}
Kyle's Lambda: {metrics['kyle_lambda']:.2f} Kyle's Lambda: {metrics['kyle_lambda']:.2f}
What does this tell us about: What does this tell us about:
1. Current market sentiment 1. Current market sentiment
2. Potential price direction 2. Potential price direction
@ -629,7 +593,7 @@ class TickDataAgent(BaseMarketAgent):
except Exception as e: except Exception as e:
logger.error( logger.error(
f"Error in tick analysis: {str(e)}", exc_info=True f"Error in tick analysis: {e!s}", exc_info=True
) )
return None return None
@ -659,8 +623,8 @@ class LatencyArbitrageAgent(BaseMarketAgent):
} }
def calculate_effective_prices( def calculate_effective_prices(
self, ticker: Dict, venue: str self, ticker: dict, venue: str
) -> Tuple[float, float]: ) -> tuple[float, float]:
"""Calculate effective prices including fees""" """Calculate effective prices including fees"""
fee = self.fee_structure[venue] fee = self.fee_structure[venue]
return ( return (
@ -669,8 +633,8 @@ class LatencyArbitrageAgent(BaseMarketAgent):
) )
def calculate_arbitrage_metrics( def calculate_arbitrage_metrics(
self, prices: Dict[str, Dict] self, prices: dict[str, dict]
) -> Dict: ) -> dict:
opportunities = [] opportunities = []
for venue1 in prices: for venue1 in prices:
@ -818,7 +782,7 @@ class LatencyArbitrageAgent(BaseMarketAgent):
) )
except Exception as e: except Exception as e:
logger.error(f"Error in arbitrage analysis: {str(e)}") logger.error(f"Error in arbitrage analysis: {e!s}")
return None return None
@ -841,7 +805,7 @@ class SwarmCoordinator:
with self.lock: with self.lock:
self.signal_processors.append(processor) self.signal_processors.append(processor)
def process_signals(self, signals: List[MarketSignal]): def process_signals(self, signals: list[MarketSignal]):
"""Process signals through all registered processors""" """Process signals through all registered processors"""
if not signals: if not signals:
return return
@ -855,8 +819,8 @@ class SwarmCoordinator:
logger.error(f"Error in signal processing: {e}") logger.error(f"Error in signal processing: {e}")
def aggregate_signals( def aggregate_signals(
self, signals: List[MarketSignal] self, signals: list[MarketSignal]
) -> Dict[str, Any]: ) -> dict[str, Any]:
"""Aggregate multiple signals into a combined market view""" """Aggregate multiple signals into a combined market view"""
if not signals: if not signals:
return {} return {}
@ -925,7 +889,7 @@ class SwarmCoordinator:
return aggregated return aggregated
def start(self, symbols: List[str], interval: float = 1.0): def start(self, symbols: list[str], interval: float = 1.0):
"""Start the swarm monitoring system""" """Start the swarm monitoring system"""
if self.running: if self.running:
logger.warning("Swarm is already running") logger.warning("Swarm is already running")
@ -1010,7 +974,7 @@ class SwarmCoordinator:
logger.info("Swarm stopped") logger.info("Swarm stopped")
def market_making_processor(signals: List[MarketSignal]): def market_making_processor(signals: list[MarketSignal]):
"""Enhanced signal processor with LLM analysis integration""" """Enhanced signal processor with LLM analysis integration"""
for signal in signals: for signal in signals:
if signal.confidence > 0.8: if signal.confidence > 0.8:

@ -1,25 +1,32 @@
import inspect
import json
import os import os
from typing import List, Dict, Any, Optional, Callable, get_type_hints import typing
from dataclasses import dataclass, field from dataclasses import dataclass, field
import json
from datetime import datetime from datetime import datetime
import inspect from typing import (
import typing Any,
from typing import Union Callable,
from swarms import Agent Optional,
Union,
get_type_hints,
)
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent
@dataclass @dataclass
class ToolDefinition: class ToolDefinition:
name: str name: str
description: str description: str
parameters: Dict[str, Any] parameters: dict[str, Any]
required_params: List[str] required_params: list[str]
callable: Optional[Callable] = None callable: Optional[Callable] = None
def extract_type_hints(func: Callable) -> Dict[str, Any]: def extract_type_hints(func: Callable) -> dict[str, Any]:
"""Extract parameter types from function type hints.""" """Extract parameter types from function type hints."""
return typing.get_type_hints(func) return typing.get_type_hints(func)
@ -81,7 +88,7 @@ class FunctionSpec:
name: str name: str
description: str description: str
parameters: Dict[ parameters: dict[
str, dict str, dict
] # Contains type and description for each parameter ] # Contains type and description for each parameter
return_type: str return_type: str
@ -94,7 +101,7 @@ class ExecutionStep:
step_id: int step_id: int
function_name: str function_name: str
parameters: Dict[str, Any] parameters: dict[str, Any]
expected_output: str expected_output: str
completed: bool = False completed: bool = False
result: Any = None result: Any = None
@ -105,10 +112,10 @@ class ExecutionContext:
"""Maintains state during execution.""" """Maintains state during execution."""
task: str task: str
steps: List[ExecutionStep] = field(default_factory=list) steps: list[ExecutionStep] = field(default_factory=list)
results: Dict[int, Any] = field(default_factory=dict) results: dict[int, Any] = field(default_factory=dict)
current_step: int = 0 current_step: int = 0
history: List[Dict[str, Any]] = field(default_factory=list) history: list[dict[str, Any]] = field(default_factory=list)
def func(): def func():
@ -121,7 +128,7 @@ hints = get_type_hints(func)
class ToolAgent: class ToolAgent:
def __init__( def __init__(
self, self,
functions: List[Callable], functions: list[Callable],
openai_api_key: str, openai_api_key: str,
model_name: str = "gpt-4", model_name: str = "gpt-4",
temperature: float = 0.1, temperature: float = 0.1,
@ -145,8 +152,8 @@ class ToolAgent:
) )
def _analyze_functions( def _analyze_functions(
self, functions: List[Callable] self, functions: list[Callable]
) -> Dict[str, FunctionSpec]: ) -> dict[str, FunctionSpec]:
"""Analyze functions to create detailed specifications.""" """Analyze functions to create detailed specifications."""
specs = {} specs = {}
for func in functions: for func in functions:
@ -254,7 +261,7 @@ Always:
""" """
def _execute_function( def _execute_function(
self, spec: FunctionSpec, parameters: Dict[str, Any] self, spec: FunctionSpec, parameters: dict[str, Any]
) -> Any: ) -> Any:
"""Execute a function with type checking.""" """Execute a function with type checking."""
converted_params = {} converted_params = {}
@ -269,12 +276,12 @@ Always:
converted_params[name] = value converted_params[name] = value
except (ValueError, TypeError) as e: except (ValueError, TypeError) as e:
raise ValueError( raise ValueError(
f"Parameter '{name}' conversion failed: {str(e)}" f"Parameter '{name}' conversion failed: {e!s}"
) )
return self.functions[spec.name](**converted_params) return self.functions[spec.name](**converted_params)
def run(self, task: str) -> Dict[str, Any]: def run(self, task: str) -> dict[str, Any]:
"""Execute task with planning and step-by-step execution.""" """Execute task with planning and step-by-step execution."""
context = ExecutionContext(task=task) context = ExecutionContext(task=task)
execution_log = { execution_log = {
@ -326,7 +333,7 @@ Always:
Function: {step.function_name} Function: {step.function_name}
Result: {json.dumps(result)} Result: {json.dumps(result)}
Remaining steps: {len(context.steps) - context.current_step - 1} Remaining steps: {len(context.steps) - context.current_step - 1}
Analyze the result and decide next action. Analyze the result and decide next action.
""" """
@ -363,7 +370,7 @@ Always:
context.current_step += 1 context.current_step += 1
except Exception as e: except Exception as e:
print(f"Error in step {step.step_id}: {str(e)}") print(f"Error in step {step.step_id}: {e!s}")
execution_log["steps"].append( execution_log["steps"].append(
{ {
"step_id": step.step_id, "step_id": step.step_id,
@ -378,7 +385,7 @@ Always:
final_prompt = f""" final_prompt = f"""
Task completed. Results: Task completed. Results:
{json.dumps(context.results, indent=2)} {json.dumps(context.results, indent=2)}
Provide final analysis and recommendations. Provide final analysis and recommendations.
""" """

@ -31,4 +31,4 @@ try:
print(results) print(results)
except Exception as e: except Exception as e:
print(f"An error occurred: {str(e)}") print(f"An error occurred: {e!s}")

@ -31,4 +31,4 @@ try:
print(results) print(results)
except Exception as e: except Exception as e:
print(f"An error occurred: {str(e)}") print(f"An error occurred: {e!s}")

@ -1,31 +1,31 @@
""" """
- For each diagnosis, pull lab results, - For each diagnosis, pull lab results,
- egfr - egfr
- for each diagnosis, pull lab ranges, - for each diagnosis, pull lab ranges,
- pull ranges for diagnosis - pull ranges for diagnosis
- if the diagnosis is x, then the lab ranges should be a to b - if the diagnosis is x, then the lab ranges should be a to b
- train the agents, increase the load of input - train the agents, increase the load of input
- medical history sent to the agent - medical history sent to the agent
- setup rag for the agents - setup rag for the agents
- run the first agent -> kidney disease -> don't know the stage -> stage 2 -> lab results -> indicative of stage 3 -> the case got elavated -> - run the first agent -> kidney disease -> don't know the stage -> stage 2 -> lab results -> indicative of stage 3 -> the case got elavated ->
- how to manage diseases and by looking at correlating lab, docs, diagnoses - how to manage diseases and by looking at correlating lab, docs, diagnoses
- put docs in rag -> - put docs in rag ->
- monitoring, evaluation, and treatment - monitoring, evaluation, and treatment
- can we confirm for every diagnosis -> monitoring, evaluation, and treatment, specialized for these things - can we confirm for every diagnosis -> monitoring, evaluation, and treatment, specialized for these things
- find diagnosis -> or have diagnosis, -> for each diagnosis are there evidence of those 3 things - find diagnosis -> or have diagnosis, -> for each diagnosis are there evidence of those 3 things
- swarm of those 4 agents, -> - swarm of those 4 agents, ->
- fda api for healthcare for commerically available papers - fda api for healthcare for commerically available papers
- -
""" """
from datetime import datetime from datetime import datetime
from swarms import Agent, AgentRearrange, create_file_in_folder
from swarm_models import OllamaModel from swarm_models import OllamaModel
from swarms import Agent, AgentRearrange, create_file_in_folder
model = OllamaModel(model_name="llama3.2") model = OllamaModel(model_name="llama3.2")
chief_medical_officer = Agent( chief_medical_officer = Agent(
@ -40,14 +40,14 @@ chief_medical_officer = Agent(
- Suggesting treatment plans based on team input - Suggesting treatment plans based on team input
- Identifying when additional specialists need to be consulted - Identifying when additional specialists need to be consulted
- For each diferrential diagnosis provide minimum lab ranges to meet that diagnosis or be indicative of that diagnosis minimum and maximum - For each diferrential diagnosis provide minimum lab ranges to meet that diagnosis or be indicative of that diagnosis minimum and maximum
Format all responses with clear sections for: Format all responses with clear sections for:
- Initial Assessment (include preliminary ICD-10 codes for symptoms) - Initial Assessment (include preliminary ICD-10 codes for symptoms)
- Differential Diagnoses (with corresponding ICD-10 codes) - Differential Diagnoses (with corresponding ICD-10 codes)
- Specialist Consultations Needed - Specialist Consultations Needed
- Recommended Next Steps - Recommended Next Steps
""", """,
llm=model, llm=model,
max_loops=1, max_loops=1,
@ -56,12 +56,12 @@ chief_medical_officer = Agent(
virologist = Agent( virologist = Agent(
agent_name="Virologist", agent_name="Virologist",
system_prompt="""You are a specialist in viral diseases. For each case, provide: system_prompt="""You are a specialist in viral diseases. For each case, provide:
Clinical Analysis: Clinical Analysis:
- Detailed viral symptom analysis - Detailed viral symptom analysis
- Disease progression timeline - Disease progression timeline
- Risk factors and complications - Risk factors and complications
Coding Requirements: Coding Requirements:
- List relevant ICD-10 codes for: - List relevant ICD-10 codes for:
* Confirmed viral conditions * Confirmed viral conditions
@ -71,7 +71,7 @@ virologist = Agent(
- Include both: - Include both:
* Primary diagnostic codes * Primary diagnostic codes
* Secondary condition codes * Secondary condition codes
Document all findings using proper medical coding standards and include rationale for code selection.""", Document all findings using proper medical coding standards and include rationale for code selection.""",
llm=model, llm=model,
max_loops=1, max_loops=1,
@ -80,14 +80,14 @@ virologist = Agent(
internist = Agent( internist = Agent(
agent_name="Internist", agent_name="Internist",
system_prompt="""You are an Internal Medicine specialist responsible for comprehensive evaluation. system_prompt="""You are an Internal Medicine specialist responsible for comprehensive evaluation.
For each case, provide: For each case, provide:
Clinical Assessment: Clinical Assessment:
- System-by-system review - System-by-system review
- Vital signs analysis - Vital signs analysis
- Comorbidity evaluation - Comorbidity evaluation
Medical Coding: Medical Coding:
- ICD-10 codes for: - ICD-10 codes for:
* Primary conditions * Primary conditions
@ -96,7 +96,7 @@ internist = Agent(
* Chronic conditions * Chronic conditions
* Signs and symptoms * Signs and symptoms
- Include hierarchical condition category (HCC) codes where applicable - Include hierarchical condition category (HCC) codes where applicable
Document supporting evidence for each code selected.""", Document supporting evidence for each code selected.""",
llm=model, llm=model,
max_loops=1, max_loops=1,
@ -105,20 +105,20 @@ internist = Agent(
medical_coder = Agent( medical_coder = Agent(
agent_name="Medical Coder", agent_name="Medical Coder",
system_prompt="""You are a certified medical coder responsible for: system_prompt="""You are a certified medical coder responsible for:
Primary Tasks: Primary Tasks:
1. Reviewing all clinical documentation 1. Reviewing all clinical documentation
2. Assigning accurate ICD-10 codes 2. Assigning accurate ICD-10 codes
3. Ensuring coding compliance 3. Ensuring coding compliance
4. Documenting code justification 4. Documenting code justification
Coding Process: Coding Process:
- Review all specialist inputs - Review all specialist inputs
- Identify primary and secondary diagnoses - Identify primary and secondary diagnoses
- Assign appropriate ICD-10 codes - Assign appropriate ICD-10 codes
- Document supporting evidence - Document supporting evidence
- Note any coding queries - Note any coding queries
Output Format: Output Format:
1. Primary Diagnosis Codes 1. Primary Diagnosis Codes
- ICD-10 code - ICD-10 code
@ -136,12 +136,12 @@ medical_coder = Agent(
synthesizer = Agent( synthesizer = Agent(
agent_name="Diagnostic Synthesizer", agent_name="Diagnostic Synthesizer",
system_prompt="""You are responsible for creating the final diagnostic and coding assessment. system_prompt="""You are responsible for creating the final diagnostic and coding assessment.
Synthesis Requirements: Synthesis Requirements:
1. Integrate all specialist findings 1. Integrate all specialist findings
2. Reconcile any conflicting diagnoses 2. Reconcile any conflicting diagnoses
3. Verify coding accuracy and completeness 3. Verify coding accuracy and completeness
Final Report Sections: Final Report Sections:
1. Clinical Summary 1. Clinical Summary
- Primary diagnosis with ICD-10 - Primary diagnosis with ICD-10
@ -155,7 +155,7 @@ synthesizer = Agent(
- Additional testing needed - Additional testing needed
- Follow-up care - Follow-up care
- Documentation improvements needed - Documentation improvements needed
Include confidence levels and evidence quality for all diagnoses and codes.""", Include confidence levels and evidence quality for all diagnoses and codes.""",
llm=model, llm=model,
max_loops=1, max_loops=1,
@ -228,10 +228,10 @@ if __name__ == "__main__":
Patient: 45-year-old White Male Patient: 45-year-old White Male
Lab Results: Lab Results:
- egfr - egfr
- 59 ml / min / 1.73 - 59 ml / min / 1.73
- non african-american - non african-american
""" """
# Add timestamp to the patient case # Add timestamp to the patient case

@ -1,7 +1,7 @@
from swarms.agents.openai_assistant import OpenAIAssistant
from swarms.prompts.finance_agent_sys_prompt import ( from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT, FINANCIAL_AGENT_SYS_PROMPT,
) )
from swarms.agents.openai_assistant import OpenAIAssistant
agent = OpenAIAssistant( agent = OpenAIAssistant(
name="test", instructions=FINANCIAL_AGENT_SYS_PROMPT name="test", instructions=FINANCIAL_AGENT_SYS_PROMPT

@ -1,10 +1,12 @@
import os import os
from swarms import Agent
from swarm_models import OpenAIChat
from dotenv import load_dotenv from dotenv import load_dotenv
from swarm_models import OpenAIChat
from swarms import Agent
# Custom system prompt for VC legal document generation # Custom system prompt for VC legal document generation
VC_LEGAL_AGENT_PROMPT = """You are a specialized legal document assistant focusing on venture capital documentation. VC_LEGAL_AGENT_PROMPT = """You are a specialized legal document assistant focusing on venture capital documentation.
Your role is to help draft preliminary versions of common VC legal documents while adhering to these guidelines: Your role is to help draft preliminary versions of common VC legal documents while adhering to these guidelines:
1. Always include standard legal disclaimers 1. Always include standard legal disclaimers
@ -71,14 +73,14 @@ def generate_legal_document(agent, document_type, parameters):
prompt = f""" prompt = f"""
Generate a {document_type} with the following parameters: Generate a {document_type} with the following parameters:
{parameters} {parameters}
Please follow these steps: Please follow these steps:
1. Create initial draft 1. Create initial draft
2. Review for completeness 2. Review for completeness
3. Add necessary legal disclaimers 3. Add necessary legal disclaimers
4. Verify all required sections 4. Verify all required sections
5. Output <DONE> when complete 5. Output <DONE> when complete
Include [REQUIRES LEGAL REVIEW] tags for sections needing attorney attention. Include [REQUIRES LEGAL REVIEW] tags for sections needing attorney attention.
""" """

@ -1,7 +1,9 @@
import os import os
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, AgentRearrange
# Get the OpenAI API key from the environment variable # Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY") api_key = os.getenv("OPENAI_API_KEY")
@ -27,7 +29,7 @@ matchmaker_agent = Agent(
- Personal identification numbers - Personal identification numbers
- Workplace specifics - Workplace specifics
</restricted_information> </restricted_information>
<shareable_information> <shareable_information>
- First name only - First name only
- Age range (not exact birth date) - Age range (not exact birth date)
@ -97,7 +99,7 @@ profile_analyzer = Agent(
- Access logs must be maintained - Access logs must be maintained
- Data retention policies must be followed - Data retention policies must be followed
</storage> </storage>
<processing> <processing>
- Use anonymized IDs for internal processing - Use anonymized IDs for internal processing
- Apply privacy-preserving analysis techniques - Apply privacy-preserving analysis techniques
@ -113,7 +115,7 @@ profile_analyzer = Agent(
- Lifestyle compatibility - Lifestyle compatibility
- Communication style matching - Communication style matching
</compatibility_metrics> </compatibility_metrics>
<red_flags> <red_flags>
- Inconsistent information - Inconsistent information
- Suspicious behavior patterns - Suspicious behavior patterns
@ -220,9 +222,9 @@ connection_facilitator = Agent(
# Swarm-Level Prompt (Collaboration Prompt) # Swarm-Level Prompt (Collaboration Prompt)
swarm_prompt = """ swarm_prompt = """
As a dating platform swarm, your collective goal is to facilitate meaningful connections while maintaining As a dating platform swarm, your collective goal is to facilitate meaningful connections while maintaining
the highest standards of privacy and safety. The MatchmakerAgent oversees the entire matching process, the highest standards of privacy and safety. The MatchmakerAgent oversees the entire matching process,
coordinating between the ProfileAnalyzer who deeply understands user compatibility, and the ConnectionFacilitator coordinating between the ProfileAnalyzer who deeply understands user compatibility, and the ConnectionFacilitator
who manages the development of connections. Together, you must ensure that: who manages the development of connections. Together, you must ensure that:
1. User privacy is maintained at all times 1. User privacy is maintained at all times
@ -252,9 +254,9 @@ agent_system = AgentRearrange(
# Example task for the swarm # Example task for the swarm
task = f""" task = f"""
{swarm_prompt} {swarm_prompt}
Process a new batch of user profiles and identify potential matches while ensuring all privacy protocols Process a new batch of user profiles and identify potential matches while ensuring all privacy protocols
are followed. For each potential match, provide compatibility reasoning and suggested conversation are followed. For each potential match, provide compatibility reasoning and suggested conversation
starters without revealing any restricted information. starters without revealing any restricted information.
""" """

@ -1,7 +1,7 @@
import os import os
import uuid import uuid
from datetime import datetime from datetime import datetime
from typing import Dict, List, Optional from typing import Optional
from qdrant_client import QdrantClient from qdrant_client import QdrantClient
from qdrant_client.http import models from qdrant_client.http import models
@ -59,8 +59,8 @@ class QdrantMemory:
def add( def add(
self, self,
text: str, text: str,
embedding: List[float], embedding: list[float],
metadata: Optional[Dict] = None, metadata: Optional[dict] = None,
) -> str: ) -> str:
"""Add a memory to the store. """Add a memory to the store.
@ -95,10 +95,10 @@ class QdrantMemory:
def query( def query(
self, self,
query_embedding: List[float], query_embedding: list[float],
limit: int = 5, limit: int = 5,
score_threshold: float = 0.7, score_threshold: float = 0.7,
) -> List[Dict]: ) -> list[dict]:
"""Query memories based on vector similarity. """Query memories based on vector similarity.
Args: Args:

@ -3,17 +3,19 @@ Zoe - Real Estate Agent
""" """
from typing import Optional, Dict, Any, List import json
import os
from dataclasses import dataclass from dataclasses import dataclass
from datetime import datetime from datetime import datetime
import os from enum import Enum
import json from typing import Any, Optional
import requests import requests
from dotenv import load_dotenv
from loguru import logger from loguru import logger
from swarms import Agent
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from dotenv import load_dotenv
from enum import Enum from swarms import Agent
# Configure loguru logger # Configure loguru logger
logger.add( logger.add(
@ -52,8 +54,8 @@ class PropertyListing:
lat: float lat: float
lng: float lng: float
description: Optional[str] = None description: Optional[str] = None
features: Optional[List[str]] = None features: Optional[list[str]] = None
images: Optional[List[str]] = None images: Optional[list[str]] = None
class PropertyRadarAPI: class PropertyRadarAPI:
@ -78,13 +80,13 @@ class PropertyRadarAPI:
def search_properties( def search_properties(
self, self,
max_price: float = 10_000_000, max_price: float = 10_000_000,
property_types: List[PropertyType] = None, property_types: Optional[list[PropertyType]] = None,
location: Dict[str, Any] = None, location: Optional[dict[str, Any]] = None,
min_sqft: Optional[float] = None, min_sqft: Optional[float] = None,
max_sqft: Optional[float] = None, max_sqft: Optional[float] = None,
page: int = 1, page: int = 1,
limit: int = 20, limit: int = 20,
) -> List[PropertyListing]: ) -> list[PropertyListing]:
""" """
Search for commercial properties using PropertyRadar API Search for commercial properties using PropertyRadar API
@ -163,7 +165,7 @@ class PropertyRadarAPI:
] ]
except requests.RequestException as e: except requests.RequestException as e:
logger.error(f"Error fetching properties: {str(e)}") logger.error(f"Error fetching properties: {e!s}")
raise raise
@ -223,7 +225,7 @@ class CommercialRealEstateAgent:
3. Provide detailed analysis of property features, location benefits, and potential ROI 3. Provide detailed analysis of property features, location benefits, and potential ROI
4. Consider local market conditions and growth potential 4. Consider local market conditions and growth potential
5. Verify zoning compliance and restrictions 5. Verify zoning compliance and restrictions
When analyzing properties, consider: When analyzing properties, consider:
- Current market valuations - Current market valuations
- Local business development plans - Local business development plans
@ -234,11 +236,11 @@ class CommercialRealEstateAgent:
def search_properties( def search_properties(
self, self,
max_price: float = 10_000_000, max_price: float = 10_000_000,
property_types: List[PropertyType] = None, property_types: Optional[list[PropertyType]] = None,
location: Dict[str, Any] = None, location: Optional[dict[str, Any]] = None,
min_sqft: Optional[float] = None, min_sqft: Optional[float] = None,
max_sqft: Optional[float] = None, max_sqft: Optional[float] = None,
) -> List[Dict[str, Any]]: ) -> list[dict[str, Any]]:
""" """
Search for properties and provide analysis Search for properties and provide analysis
@ -286,7 +288,7 @@ class CommercialRealEstateAgent:
except Exception as e: except Exception as e:
logger.error( logger.error(
f"Error in property search and analysis: {str(e)}" f"Error in property search and analysis: {e!s}"
) )
raise raise

@ -1,8 +1,10 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import Agent, SequentialWorkflow
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, SequentialWorkflow
load_dotenv() load_dotenv()
# Get the OpenAI API key from the environment variable # Get the OpenAI API key from the environment variable

@ -1,8 +1,10 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import Agent, SequentialWorkflow
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, SequentialWorkflow
load_dotenv() load_dotenv()
# Get the OpenAI API key from the environment variable # Get the OpenAI API key from the environment variable

@ -1,8 +1,10 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import Agent, SequentialWorkflow
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, SequentialWorkflow
load_dotenv() load_dotenv()
# Get the OpenAI API key from the environment variable # Get the OpenAI API key from the environment variable

@ -1,8 +1,10 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import Agent, SequentialWorkflow
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, SequentialWorkflow
load_dotenv() load_dotenv()
# Get the OpenAI API key from the environment variable # Get the OpenAI API key from the environment variable

@ -1,21 +1,22 @@
from dataclasses import dataclass
from typing import List, Optional, Dict, Any
from datetime import datetime
import asyncio import asyncio
from loguru import logger
import json import json
import base58 from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal from decimal import Decimal
from typing import Any, Optional
# Swarms imports import aiohttp
from swarms import Agent import base58
from anchorpy import Provider, Wallet
from loguru import logger
from solders.keypair import Keypair
# Solana imports # Solana imports
from solders.rpc.responses import GetTransactionResp from solders.rpc.responses import GetTransactionResp
from solders.transaction import Transaction from solders.transaction import Transaction
from anchorpy import Provider, Wallet
from solders.keypair import Keypair # Swarms imports
import aiohttp from swarms import Agent
# Specialized Solana Analysis System Prompt # Specialized Solana Analysis System Prompt
SOLANA_ANALYSIS_PROMPT = """You are a specialized Solana blockchain analyst agent. Your role is to: SOLANA_ANALYSIS_PROMPT = """You are a specialized Solana blockchain analyst agent. Your role is to:
@ -74,14 +75,14 @@ class TransactionData:
to_address: str to_address: str
program_id: str program_id: str
instruction_data: Optional[str] = None instruction_data: Optional[str] = None
program_logs: List[str] = None program_logs: list[str] = None
@property @property
def sol_amount(self) -> Decimal: def sol_amount(self) -> Decimal:
"""Convert lamports to SOL""" """Convert lamports to SOL"""
return Decimal(self.lamports) / Decimal(1e9) return Decimal(self.lamports) / Decimal(1e9)
def to_dict(self) -> Dict[str, Any]: def to_dict(self) -> dict[str, Any]:
"""Convert transaction data to dictionary for agent analysis""" """Convert transaction data to dictionary for agent analysis"""
return { return {
"signature": self.signature, "signature": self.signature,
@ -132,7 +133,7 @@ class SolanaSwarmAgent:
async def analyze_transaction( async def analyze_transaction(
self, tx_data: TransactionData self, tx_data: TransactionData
) -> Dict[str, Any]: ) -> dict[str, Any]:
"""Analyze a transaction using the specialized agent""" """Analyze a transaction using the specialized agent"""
try: try:
# Update recent transactions for pattern analysis # Update recent transactions for pattern analysis
@ -192,7 +193,7 @@ class SolanaSwarmAgent:
return json.loads(analysis) return json.loads(analysis)
except Exception as e: except Exception as e:
logger.error(f"Error in agent analysis: {str(e)}") logger.error(f"Error in agent analysis: {e!s}")
return { return {
"analysis_type": "error", "analysis_type": "error",
"severity": "low", "severity": "low",
@ -258,7 +259,7 @@ class SolanaTransactionMonitor:
), ),
) )
except Exception as e: except Exception as e:
logger.error(f"Failed to parse transaction: {str(e)}") logger.error(f"Failed to parse transaction: {e!s}")
return None return None
async def start_monitoring(self): async def start_monitoring(self):
@ -323,7 +324,7 @@ class SolanaTransactionMonitor:
except Exception as e: except Exception as e:
logger.error( logger.error(
f"Error processing message: {str(e)}" f"Error processing message: {e!s}"
) )
continue continue

@ -1,10 +1,10 @@
from datetime import datetime
import json import json
import time
from dataclasses import dataclass
from datetime import datetime, timezone
import requests import requests
from loguru import logger from loguru import logger
from dataclasses import dataclass
from datetime import timezone
import time
from requests.adapters import HTTPAdapter from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry from urllib3.util.retry import Retry
@ -86,7 +86,7 @@ def get_working_endpoint(session: requests.Session) -> str:
return endpoint return endpoint
except Exception as e: except Exception as e:
logger.warning( logger.warning(
f"Endpoint {endpoint} failed health check: {str(e)}" f"Endpoint {endpoint} failed health check: {e!s}"
) )
continue continue
@ -189,7 +189,7 @@ def fetch_wallet_transactions(wallet_address: str) -> str:
except Exception as e: except Exception as e:
logger.error( logger.error(
f"Error during transaction fetch: {str(e)}" f"Error during transaction fetch: {e!s}"
) )
# Try to get a new endpoint if the current one fails # Try to get a new endpoint if the current one fails
api_endpoint = get_working_endpoint(session) api_endpoint = get_working_endpoint(session)
@ -217,7 +217,7 @@ def fetch_wallet_transactions(wallet_address: str) -> str:
) )
tx_data = response.json() tx_data = response.json()
if "result" in tx_data and tx_data["result"]: if tx_data.get("result"):
enriched_transactions.append( enriched_transactions.append(
{ {
"signature": tx["signature"], "signature": tx["signature"],
@ -240,7 +240,7 @@ def fetch_wallet_transactions(wallet_address: str) -> str:
except Exception as e: except Exception as e:
logger.warning( logger.warning(
f"Failed to fetch details for transaction {tx['signature']}: {str(e)}" f"Failed to fetch details for transaction {tx['signature']}: {e!s}"
) )
continue continue
@ -272,7 +272,7 @@ def fetch_wallet_transactions(wallet_address: str) -> str:
except Exception as e: except Exception as e:
error = TransactionError( error = TransactionError(
error_type="UNKNOWN_ERROR", error_type="UNKNOWN_ERROR",
message=f"An unexpected error occurred: {str(e)}", message=f"An unexpected error occurred: {e!s}",
) )
logger.error(f"Unexpected error: {error.message}") logger.error(f"Unexpected error: {error.message}")
return json.dumps( return json.dumps(
@ -292,4 +292,4 @@ if __name__ == "__main__":
result = fetch_wallet_transactions(wallet) result = fetch_wallet_transactions(wallet)
print(json.dumps(json.loads(result), indent=2)) print(json.dumps(json.loads(result), indent=2))
except Exception as e: except Exception as e:
logger.error(f"Failed to fetch transactions: {str(e)}") logger.error(f"Failed to fetch transactions: {e!s}")

@ -1,12 +1,11 @@
from typing import List
from datetime import datetime
import json import json
import random
import time
from dataclasses import dataclass
from datetime import datetime, timezone
import requests import requests
from loguru import logger from loguru import logger
from dataclasses import dataclass
from datetime import timezone
import time
import random
# Configure loguru logger # Configure loguru logger
logger.add( logger.add(
@ -43,7 +42,7 @@ class SolanaAPIException(Exception):
class RPCEndpointManager: class RPCEndpointManager:
"""Manages RPC endpoints and handles switching between them""" """Manages RPC endpoints and handles switching between them"""
def __init__(self, endpoints: List[str]): def __init__(self, endpoints: list[str]):
self.endpoints = endpoints.copy() self.endpoints = endpoints.copy()
self.current_endpoint = self.endpoints[0] self.current_endpoint = self.endpoints[0]
self.last_request_time = 0 self.last_request_time = 0
@ -132,20 +131,20 @@ def make_request(
requests.exceptions.ConnectionError, requests.exceptions.ConnectionError,
) as e: ) as e:
logger.warning( logger.warning(
f"Connection error with {endpoint}: {str(e)}" f"Connection error with {endpoint}: {e!s}"
) )
endpoint_manager.switch_endpoint() endpoint_manager.switch_endpoint()
continue continue
except Exception as e: except Exception as e:
last_error = e last_error = e
logger.warning(f"Request failed: {str(e)}") logger.warning(f"Request failed: {e!s}")
endpoint_manager.switch_endpoint() endpoint_manager.switch_endpoint()
time.sleep(1) time.sleep(1)
continue continue
raise SolanaAPIException( raise SolanaAPIException(
f"All retry attempts failed. Last error: {str(last_error)}" f"All retry attempts failed. Last error: {last_error!s}"
) )
@ -231,7 +230,7 @@ def fetch_wallet_transactions(
tx_data = make_request(endpoint_manager, tx_payload) tx_data = make_request(endpoint_manager, tx_payload)
if "result" in tx_data and tx_data["result"]: if tx_data.get("result"):
result = tx_data["result"] result = tx_data["result"]
enriched_tx = { enriched_tx = {
"signature": tx["signature"], "signature": tx["signature"],
@ -257,7 +256,7 @@ def fetch_wallet_transactions(
except Exception as e: except Exception as e:
logger.warning( logger.warning(
f"Failed to process transaction {tx['signature']}: {str(e)}" f"Failed to process transaction {tx['signature']}: {e!s}"
) )
continue continue
@ -299,4 +298,4 @@ if __name__ == "__main__":
result = fetch_wallet_transactions(wallet) result = fetch_wallet_transactions(wallet)
print(result) print(result)
except Exception as e: except Exception as e:
logger.error(f"Failed to fetch transactions: {str(e)}") logger.error(f"Failed to fetch transactions: {e!s}")

@ -7,11 +7,12 @@ Todo
""" """
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat, OpenAIFunctionCaller
from pydantic import BaseModel from pydantic import BaseModel
from typing import List from swarm_models import OpenAIChat, OpenAIFunctionCaller
from swarms import Agent, AgentRearrange
class CollegeLog(BaseModel): class CollegeLog(BaseModel):
@ -21,7 +22,7 @@ class CollegeLog(BaseModel):
class CollegesRecommendation(BaseModel): class CollegesRecommendation(BaseModel):
colleges: List[CollegeLog] colleges: list[CollegeLog]
reasoning: str reasoning: str
@ -46,10 +47,10 @@ You are a college selection final decision maker. Your role is to:
4. Provide clear rationale for each recommendation 4. Provide clear rationale for each recommendation
5. Include specific action items for each selected school 5. Include specific action items for each selected school
6. Outline next steps in the application process 6. Outline next steps in the application process
Focus on creating actionable, well-reasoned final recommendations that Focus on creating actionable, well-reasoned final recommendations that
balance all relevant factors and stakeholder input. balance all relevant factors and stakeholder input.
""" """
function_caller = OpenAIFunctionCaller( function_caller = OpenAIFunctionCaller(
@ -69,8 +70,8 @@ profile_analyzer_agent = Agent(
4. Assess leadership experiences and community involvement 4. Assess leadership experiences and community involvement
5. Determine student's preferences for college environment, location, and programs 5. Determine student's preferences for college environment, location, and programs
6. Create a comprehensive student profile summary 6. Create a comprehensive student profile summary
Always consider both quantitative metrics (GPA, test scores) and qualitative aspects Always consider both quantitative metrics (GPA, test scores) and qualitative aspects
(personal growth, challenges overcome, unique perspectives).""", (personal growth, challenges overcome, unique perspectives).""",
llm=model, llm=model,
max_loops=1, max_loops=1,
@ -92,7 +93,7 @@ college_research_agent = Agent(
4. Evaluate college-specific opportunities and resources 4. Evaluate college-specific opportunities and resources
5. Consider financial aid availability and scholarship opportunities 5. Consider financial aid availability and scholarship opportunities
6. Track historical admission data and acceptance rates 6. Track historical admission data and acceptance rates
Focus on providing accurate, comprehensive information about each institution Focus on providing accurate, comprehensive information about each institution
while considering both academic and cultural fit factors.""", while considering both academic and cultural fit factors.""",
llm=model, llm=model,
@ -115,8 +116,8 @@ college_match_agent = Agent(
4. Assess financial fit and aid opportunities 4. Assess financial fit and aid opportunities
5. Create tiered lists of reach, target, and safety schools 5. Create tiered lists of reach, target, and safety schools
6. Explain the reasoning behind each match 6. Explain the reasoning behind each match
Always provide a balanced list with realistic expectations while Always provide a balanced list with realistic expectations while
considering both student preferences and admission probability.""", considering both student preferences and admission probability.""",
llm=model, llm=model,
max_loops=1, max_loops=1,
@ -138,7 +139,7 @@ debate_moderator_agent = Agent(
4. Synthesize different viewpoints 4. Synthesize different viewpoints
5. Guide the group toward consensus 5. Guide the group toward consensus
6. Document key points of agreement and disagreement 6. Document key points of agreement and disagreement
Maintain objectivity while ensuring all important factors are thoroughly discussed Maintain objectivity while ensuring all important factors are thoroughly discussed
and evaluated.""", and evaluated.""",
llm=model, llm=model,
@ -161,7 +162,7 @@ critique_agent = Agent(
4. Assess risks and potential drawbacks 4. Assess risks and potential drawbacks
5. Provide constructive feedback on selections 5. Provide constructive feedback on selections
6. Suggest alternative options when appropriate 6. Suggest alternative options when appropriate
Focus on constructive criticism that helps improve the final college list Focus on constructive criticism that helps improve the final college list
while maintaining realistic expectations.""", while maintaining realistic expectations.""",
llm=model, llm=model,
@ -185,8 +186,8 @@ final_decision_agent = Agent(
4. Provide clear rationale for each recommendation 4. Provide clear rationale for each recommendation
5. Include specific action items for each selected school 5. Include specific action items for each selected school
6. Outline next steps in the application process 6. Outline next steps in the application process
Focus on creating actionable, well-reasoned final recommendations that Focus on creating actionable, well-reasoned final recommendations that
balance all relevant factors and stakeholder input. balance all relevant factors and stakeholder input.
""", """,
llm=model, llm=model,

@ -7,10 +7,10 @@ Todo
""" """
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarm_models import OpenAIChat, OpenAIFunctionCaller
from pydantic import BaseModel from pydantic import BaseModel
from typing import List from swarm_models import OpenAIChat, OpenAIFunctionCaller
class CollegeLog(BaseModel): class CollegeLog(BaseModel):
@ -20,7 +20,7 @@ class CollegeLog(BaseModel):
class CollegesRecommendation(BaseModel): class CollegesRecommendation(BaseModel):
colleges: List[CollegeLog] colleges: list[CollegeLog]
reasoning: str reasoning: str

@ -1,7 +1,8 @@
from typing import Optional
from pathlib import Path from pathlib import Path
from typing import Optional
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
from loguru import logger from loguru import logger
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
class LlamaIndexDB: class LlamaIndexDB:
@ -65,7 +66,7 @@ class LlamaIndexDB:
f"Successfully indexed documents from {self.data_dir}" f"Successfully indexed documents from {self.data_dir}"
) )
except Exception as e: except Exception as e:
logger.error(f"Error indexing documents: {str(e)}") logger.error(f"Error indexing documents: {e!s}")
raise raise
def query(self, query: str, **kwargs) -> str: def query(self, query: str, **kwargs) -> str:
@ -96,7 +97,7 @@ class LlamaIndexDB:
logger.info(f"Successfully queried: {query}") logger.info(f"Successfully queried: {query}")
return str(response) return str(response)
except Exception as e: except Exception as e:
logger.error(f"Error during query: {str(e)}") logger.error(f"Error during query: {e!s}")
raise raise

@ -7,11 +7,12 @@ Todo
""" """
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from swarms import Agent, SequentialWorkflow
from swarm_models import OpenAIChat, OpenAIFunctionCaller
from pydantic import BaseModel from pydantic import BaseModel
from typing import List from swarm_models import OpenAIChat, OpenAIFunctionCaller
from swarms import Agent, SequentialWorkflow
class CollegeLog(BaseModel): class CollegeLog(BaseModel):
@ -21,7 +22,7 @@ class CollegeLog(BaseModel):
class CollegesRecommendation(BaseModel): class CollegesRecommendation(BaseModel):
colleges: List[CollegeLog] colleges: list[CollegeLog]
reasoning: str reasoning: str
@ -46,10 +47,10 @@ You are a college selection final decision maker. Your role is to:
4. Provide clear rationale for each recommendation 4. Provide clear rationale for each recommendation
5. Include specific action items for each selected school 5. Include specific action items for each selected school
6. Outline next steps in the application process 6. Outline next steps in the application process
Focus on creating actionable, well-reasoned final recommendations that Focus on creating actionable, well-reasoned final recommendations that
balance all relevant factors and stakeholder input. balance all relevant factors and stakeholder input.
""" """
function_caller = OpenAIFunctionCaller( function_caller = OpenAIFunctionCaller(
@ -69,8 +70,8 @@ profile_analyzer_agent = Agent(
4. Assess leadership experiences and community involvement 4. Assess leadership experiences and community involvement
5. Determine student's preferences for college environment, location, and programs 5. Determine student's preferences for college environment, location, and programs
6. Create a comprehensive student profile summary 6. Create a comprehensive student profile summary
Always consider both quantitative metrics (GPA, test scores) and qualitative aspects Always consider both quantitative metrics (GPA, test scores) and qualitative aspects
(personal growth, challenges overcome, unique perspectives).""", (personal growth, challenges overcome, unique perspectives).""",
llm=model, llm=model,
max_loops=1, max_loops=1,
@ -92,7 +93,7 @@ college_research_agent = Agent(
4. Evaluate college-specific opportunities and resources 4. Evaluate college-specific opportunities and resources
5. Consider financial aid availability and scholarship opportunities 5. Consider financial aid availability and scholarship opportunities
6. Track historical admission data and acceptance rates 6. Track historical admission data and acceptance rates
Focus on providing accurate, comprehensive information about each institution Focus on providing accurate, comprehensive information about each institution
while considering both academic and cultural fit factors.""", while considering both academic and cultural fit factors.""",
llm=model, llm=model,
@ -115,8 +116,8 @@ college_match_agent = Agent(
4. Assess financial fit and aid opportunities 4. Assess financial fit and aid opportunities
5. Create tiered lists of reach, target, and safety schools 5. Create tiered lists of reach, target, and safety schools
6. Explain the reasoning behind each match 6. Explain the reasoning behind each match
Always provide a balanced list with realistic expectations while Always provide a balanced list with realistic expectations while
considering both student preferences and admission probability.""", considering both student preferences and admission probability.""",
llm=model, llm=model,
max_loops=1, max_loops=1,
@ -138,7 +139,7 @@ debate_moderator_agent = Agent(
4. Synthesize different viewpoints 4. Synthesize different viewpoints
5. Guide the group toward consensus 5. Guide the group toward consensus
6. Document key points of agreement and disagreement 6. Document key points of agreement and disagreement
Maintain objectivity while ensuring all important factors are thoroughly discussed Maintain objectivity while ensuring all important factors are thoroughly discussed
and evaluated.""", and evaluated.""",
llm=model, llm=model,
@ -161,7 +162,7 @@ critique_agent = Agent(
4. Assess risks and potential drawbacks 4. Assess risks and potential drawbacks
5. Provide constructive feedback on selections 5. Provide constructive feedback on selections
6. Suggest alternative options when appropriate 6. Suggest alternative options when appropriate
Focus on constructive criticism that helps improve the final college list Focus on constructive criticism that helps improve the final college list
while maintaining realistic expectations.""", while maintaining realistic expectations.""",
llm=model, llm=model,
@ -185,8 +186,8 @@ final_decision_agent = Agent(
4. Provide clear rationale for each recommendation 4. Provide clear rationale for each recommendation
5. Include specific action items for each selected school 5. Include specific action items for each selected school
6. Outline next steps in the application process 6. Outline next steps in the application process
Focus on creating actionable, well-reasoned final recommendations that Focus on creating actionable, well-reasoned final recommendations that
balance all relevant factors and stakeholder input. balance all relevant factors and stakeholder input.
""", """,
llm=model, llm=model,

@ -9,7 +9,7 @@ portfolio_analyzer = Agent(
- Assessment of fund composition and strategy alignment - Assessment of fund composition and strategy alignment
- Risk-adjusted return analysis - Risk-adjusted return analysis
- Tax efficiency considerations - Tax efficiency considerations
For each portfolio analysis: For each portfolio analysis:
1. Evaluate fund characteristics and performance metrics 1. Evaluate fund characteristics and performance metrics
2. Analyze expense ratios and fee structures 2. Analyze expense ratios and fee structures
@ -17,7 +17,7 @@ portfolio_analyzer = Agent(
4. Compare funds within same category 4. Compare funds within same category
5. Consider tax implications 5. Consider tax implications
6. Review fund manager track record and strategy consistency 6. Review fund manager track record and strategy consistency
Maintain focus on cost-efficiency and alignment with investment objectives.""", Maintain focus on cost-efficiency and alignment with investment objectives.""",
model_name="gpt-4o", model_name="gpt-4o",
max_loops=1, max_loops=1,
@ -37,7 +37,7 @@ allocation_strategist = Agent(
- Geographic and sector diversification - Geographic and sector diversification
- Rebalancing strategy development - Rebalancing strategy development
- Portfolio optimization using modern portfolio theory - Portfolio optimization using modern portfolio theory
For each allocation: For each allocation:
1. Analyze investor risk tolerance and objectives 1. Analyze investor risk tolerance and objectives
2. Develop appropriate asset class weights 2. Develop appropriate asset class weights
@ -45,7 +45,7 @@ allocation_strategist = Agent(
4. Design rebalancing triggers and schedules 4. Design rebalancing triggers and schedules
5. Consider tax-efficient fund placement 5. Consider tax-efficient fund placement
6. Account for correlation between assets 6. Account for correlation between assets
Focus on creating well-diversified portfolios aligned with client goals and risk tolerance.""", Focus on creating well-diversified portfolios aligned with client goals and risk tolerance.""",
model_name="gpt-4o", model_name="gpt-4o",
max_loops=1, max_loops=1,
@ -65,7 +65,7 @@ risk_manager = Agent(
- Correlation analysis between funds - Correlation analysis between funds
- Stress testing and scenario analysis - Stress testing and scenario analysis
- Market condition impact assessment - Market condition impact assessment
For each portfolio: For each portfolio:
1. Calculate key risk metrics (Beta, Standard Deviation, etc.) 1. Calculate key risk metrics (Beta, Standard Deviation, etc.)
2. Analyze correlation matrices 2. Analyze correlation matrices
@ -73,7 +73,7 @@ risk_manager = Agent(
4. Evaluate liquidity risks 4. Evaluate liquidity risks
5. Assess concentration risks 5. Assess concentration risks
6. Monitor factor exposures 6. Monitor factor exposures
Focus on maintaining appropriate risk levels while maximizing risk-adjusted returns.""", Focus on maintaining appropriate risk levels while maximizing risk-adjusted returns.""",
model_name="gpt-4o", model_name="gpt-4o",
max_loops=1, max_loops=1,
@ -93,7 +93,7 @@ implementation_specialist = Agent(
- Portfolio rebalancing execution - Portfolio rebalancing execution
- Trading cost analysis - Trading cost analysis
- Cash flow management - Cash flow management
For each implementation: For each implementation:
1. Select most efficient funds for desired exposure 1. Select most efficient funds for desired exposure
2. Plan tax-efficient transitions 2. Plan tax-efficient transitions
@ -101,7 +101,7 @@ implementation_specialist = Agent(
4. Optimize trade execution 4. Optimize trade execution
5. Manage cash positions 5. Manage cash positions
6. Monitor tracking error 6. Monitor tracking error
Maintain focus on minimizing costs and maximizing tax efficiency during implementation.""", Maintain focus on minimizing costs and maximizing tax efficiency during implementation.""",
model_name="gpt-4o", model_name="gpt-4o",
max_loops=1, max_loops=1,
@ -121,7 +121,7 @@ monitoring_specialist = Agent(
- Fund changes and replacements - Fund changes and replacements
- Tax loss harvesting opportunities - Tax loss harvesting opportunities
- Performance attribution analysis - Performance attribution analysis
For each review: For each review:
1. Track portfolio drift from targets 1. Track portfolio drift from targets
2. Monitor fund performance and changes 2. Monitor fund performance and changes
@ -129,7 +129,7 @@ monitoring_specialist = Agent(
4. Analyze tracking error and expenses 4. Analyze tracking error and expenses
5. Review risk metrics evolution 5. Review risk metrics evolution
6. Generate performance attribution reports 6. Generate performance attribution reports
Ensure continuous alignment with investment objectives while maintaining optimal portfolio efficiency.""", Ensure continuous alignment with investment objectives while maintaining optimal portfolio efficiency.""",
model_name="gpt-4o", model_name="gpt-4o",
max_loops=1, max_loops=1,

@ -1,9 +1,9 @@
import os import os
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat from swarm_models import OpenAIChat
from swarms import Agent, AgentRearrange
# Get the OpenAI API key from the environment variable # Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY") api_key = os.getenv("OPENAI_API_KEY")
@ -17,13 +17,13 @@ model = OpenAIChat(
boss_agent = Agent( boss_agent = Agent(
agent_name="BossAgent", agent_name="BossAgent",
system_prompt=""" system_prompt="""
You are the BossAgent responsible for managing and overseeing a swarm of agents analyzing company expenses. 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. 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, 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, 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 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 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 dynamically adapt the swarm to optimize their performance. Finally, you summarize their findings
into a coherent report. into a coherent report.
""", """,
llm=model, llm=model,
@ -40,10 +40,10 @@ boss_agent = Agent(
worker1 = Agent( worker1 = Agent(
agent_name="ExpenseAnalyzer", agent_name="ExpenseAnalyzer",
system_prompt=""" system_prompt="""
Your task is to carefully analyze the company's expense data provided to you. 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 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. (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. 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. Pay close attention to monthly recurring subscriptions, office supplies, and non-essential expenditures.
""", """,
llm=model, llm=model,
@ -60,9 +60,9 @@ worker1 = Agent(
worker2 = Agent( worker2 = Agent(
agent_name="SummaryGenerator", agent_name="SummaryGenerator",
system_prompt=""" system_prompt="""
After receiving the detailed breakdown from the ExpenseAnalyzer, 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, 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 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. 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. Be clear and to the point, emphasizing the urgency of cutting unnecessary expenses.
""", """,
@ -78,12 +78,12 @@ worker2 = Agent(
# Swarm-Level Prompt (Collaboration Prompt) # Swarm-Level Prompt (Collaboration Prompt)
swarm_prompt = """ swarm_prompt = """
As a swarm, your collective goal is to analyze the company's expenses and identify transactions that should be cut off. 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. 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 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, 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 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. 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 companys financial health. Together, your collaboration is essential to streamlining and improving the companys financial health.
""" """
@ -108,11 +108,11 @@ agent_system = AgentRearrange(
task = f""" task = f"""
{swarm_prompt} {swarm_prompt}
The company has been facing a rising number of unnecessary expenses, and the finance team needs a detailed 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. 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, Analyze the provided transaction data and create a detailed report on cost-cutting opportunities,
focusing on recurring transactions and non-essential expenditures. focusing on recurring transactions and non-essential expenditures.
""" """
# Run the swarm system with the task # Run the swarm system with the task

@ -22,13 +22,13 @@ model = OpenAIChat(
managing_director = Agent( managing_director = Agent(
agent_name="Managing-Director", agent_name="Managing-Director",
system_prompt=f""" system_prompt=f"""
As the Managing Director at Blackstone, your role is to oversee the entire investment analysis process for potential acquisitions. As the Managing Director at Blackstone, your role is to oversee the entire investment analysis process for potential acquisitions.
Your responsibilities include: Your responsibilities include:
1. Setting the overall strategy and direction for the analysis 1. Setting the overall strategy and direction for the analysis
2. Coordinating the efforts of the various team members and ensuring a comprehensive evaluation 2. Coordinating the efforts of the various team members and ensuring a comprehensive evaluation
3. Reviewing the findings and recommendations from each team member 3. Reviewing the findings and recommendations from each team member
4. Making the final decision on whether to proceed with the acquisition 4. Making the final decision on whether to proceed with the acquisition
For the current potential acquisition of {company}, direct the tasks for the team to thoroughly analyze all aspects of the company, including its financials, industry position, technology, market potential, and regulatory compliance. Provide guidance and feedback as needed to ensure a rigorous and unbiased assessment. For the current potential acquisition of {company}, direct the tasks for the team to thoroughly analyze all aspects of the company, including its financials, industry position, technology, market potential, and regulatory compliance. Provide guidance and feedback as needed to ensure a rigorous and unbiased assessment.
""", """,
llm=model, llm=model,
@ -45,7 +45,7 @@ managing_director = Agent(
vp_finance = Agent( vp_finance = Agent(
agent_name="VP-Finance", agent_name="VP-Finance",
system_prompt=f""" system_prompt=f"""
As the Vice President of Finance at Blackstone, your role is to lead the financial analysis of potential acquisitions. As the Vice President of Finance at Blackstone, your role is to lead the financial analysis of potential acquisitions.
For the current potential acquisition of {company}, your tasks include: For the current potential acquisition of {company}, your tasks include:
1. Conducting a thorough review of {company}' financial statements, including income statements, balance sheets, and cash flow statements 1. Conducting a thorough review of {company}' financial statements, including income statements, balance sheets, and cash flow statements
2. Analyzing key financial metrics such as revenue growth, profitability margins, liquidity ratios, and debt levels 2. Analyzing key financial metrics such as revenue growth, profitability margins, liquidity ratios, and debt levels
@ -72,11 +72,11 @@ industry_analyst = Agent(
As the Industry Analyst at Blackstone, your role is to provide in-depth research and analysis on the industries and markets relevant to potential acquisitions. As the Industry Analyst at Blackstone, your role is to provide in-depth research and analysis on the industries and markets relevant to potential acquisitions.
For the current potential acquisition of {company}, your tasks include: For the current potential acquisition of {company}, your tasks include:
1. Conducting a comprehensive analysis of the industrial robotics and automation solutions industry, including market size, growth rates, key trends, and future prospects 1. Conducting a comprehensive analysis of the industrial robotics and automation solutions industry, including market size, growth rates, key trends, and future prospects
2. Identifying the major players in the industry and assessing their market share, competitive strengths and weaknesses, and strategic positioning 2. Identifying the major players in the industry and assessing their market share, competitive strengths and weaknesses, and strategic positioning
3. Evaluating {company}' competitive position within the industry, including its market share, differentiation, and competitive advantages 3. Evaluating {company}' competitive position within the industry, including its market share, differentiation, and competitive advantages
4. Analyzing the key drivers and restraints for the industry, such as technological advancements, labor costs, regulatory changes, and economic conditions 4. Analyzing the key drivers and restraints for the industry, such as technological advancements, labor costs, regulatory changes, and economic conditions
5. Identifying potential risks and opportunities for {company} based on the industry analysis, such as disruptive technologies, emerging markets, or shifts in customer preferences 5. Identifying potential risks and opportunities for {company} based on the industry analysis, such as disruptive technologies, emerging markets, or shifts in customer preferences
Your analysis should provide a clear and objective assessment of the attractiveness and future potential of the industrial robotics industry, as well as {company}' positioning within it. Consider both short-term and long-term factors, and provide evidence-based insights to inform the investment decision. Your analysis should provide a clear and objective assessment of the attractiveness and future potential of the industrial robotics industry, as well as {company}' positioning within it. Consider both short-term and long-term factors, and provide evidence-based insights to inform the investment decision.
""", """,
llm=model, llm=model,
@ -95,12 +95,12 @@ tech_expert = Agent(
system_prompt=f""" system_prompt=f"""
As the Technology Expert at Blackstone, your role is to assess the technological capabilities, competitive advantages, and potential risks of companies being considered for acquisition. As the Technology Expert at Blackstone, your role is to assess the technological capabilities, competitive advantages, and potential risks of companies being considered for acquisition.
For the current potential acquisition of {company}, your tasks include: For the current potential acquisition of {company}, your tasks include:
1. Conducting a deep dive into {company}' proprietary technologies, including its robotics platforms, automation software, and AI capabilities 1. Conducting a deep dive into {company}' proprietary technologies, including its robotics platforms, automation software, and AI capabilities
2. Assessing the uniqueness, scalability, and defensibility of {company}' technology stack and intellectual property 2. Assessing the uniqueness, scalability, and defensibility of {company}' technology stack and intellectual property
3. Comparing {company}' technologies to those of its competitors and identifying any key differentiators or technology gaps 3. Comparing {company}' technologies to those of its competitors and identifying any key differentiators or technology gaps
4. Evaluating {company}' research and development capabilities, including its innovation pipeline, engineering talent, and R&D investments 4. Evaluating {company}' research and development capabilities, including its innovation pipeline, engineering talent, and R&D investments
5. Identifying any potential technology risks or disruptive threats that could impact {company}' long-term competitiveness, such as emerging technologies or expiring patents 5. Identifying any potential technology risks or disruptive threats that could impact {company}' long-term competitiveness, such as emerging technologies or expiring patents
Your analysis should provide a comprehensive assessment of {company}' technological strengths and weaknesses, as well as the sustainability of its competitive advantages. Consider both the current state of its technology and its future potential in light of industry trends and advancements. Your analysis should provide a comprehensive assessment of {company}' technological strengths and weaknesses, as well as the sustainability of its competitive advantages. Consider both the current state of its technology and its future potential in light of industry trends and advancements.
""", """,
llm=model, llm=model,
@ -124,7 +124,7 @@ market_researcher = Agent(
3. Conducting a detailed market sizing and segmentation analysis for the industrial robotics and automation markets, including identifying high-growth segments and emerging opportunities 3. Conducting a detailed market sizing and segmentation analysis for the industrial robotics and automation markets, including identifying high-growth segments and emerging opportunities
4. Evaluating the demand drivers and sales cycles for {company}' products and services, and identifying any potential risks or limitations to adoption 4. Evaluating the demand drivers and sales cycles for {company}' products and services, and identifying any potential risks or limitations to adoption
5. Developing financial projections and estimates for {company}' revenue growth potential based on the market analysis and assumptions around market share and penetration 5. Developing financial projections and estimates for {company}' revenue growth potential based on the market analysis and assumptions around market share and penetration
Your analysis should provide a data-driven assessment of the market opportunity for {company} and the feasibility of achieving our investment return targets. Consider both bottom-up and top-down market perspectives, and identify any key sensitivities or assumptions in your projections. Your analysis should provide a data-driven assessment of the market opportunity for {company} and the feasibility of achieving our investment return targets. Consider both bottom-up and top-down market perspectives, and identify any key sensitivities or assumptions in your projections.
""", """,
llm=model, llm=model,
@ -142,13 +142,13 @@ regulatory_specialist = Agent(
agent_name="Regulatory-Specialist", agent_name="Regulatory-Specialist",
system_prompt=f""" system_prompt=f"""
As the Regulatory Specialist at Blackstone, your role is to identify and assess any regulatory risks, compliance requirements, and potential legal liabilities associated with potential acquisitions. As the Regulatory Specialist at Blackstone, your role is to identify and assess any regulatory risks, compliance requirements, and potential legal liabilities associated with potential acquisitions.
For the current potential acquisition of {company}, your tasks include: For the current potential acquisition of {company}, your tasks include:
1. Identifying all relevant regulatory bodies and laws that govern the operations of {company}, including industry-specific regulations, labor laws, and environmental regulations 1. Identifying all relevant regulatory bodies and laws that govern the operations of {company}, including industry-specific regulations, labor laws, and environmental regulations
2. Reviewing {company}' current compliance policies, procedures, and track record to identify any potential gaps or areas of non-compliance 2. Reviewing {company}' current compliance policies, procedures, and track record to identify any potential gaps or areas of non-compliance
3. Assessing the potential impact of any pending or proposed changes to relevant regulations that could affect {company}' business or create additional compliance burdens 3. Assessing the potential impact of any pending or proposed changes to relevant regulations that could affect {company}' business or create additional compliance burdens
4. Evaluating the potential legal liabilities and risks associated with {company}' products, services, and operations, including product liability, intellectual property, and customer contracts 4. Evaluating the potential legal liabilities and risks associated with {company}' products, services, and operations, including product liability, intellectual property, and customer contracts
5. Providing recommendations on any regulatory or legal due diligence steps that should be taken as part of the acquisition process, as well as any post-acquisition integration considerations 5. Providing recommendations on any regulatory or legal due diligence steps that should be taken as part of the acquisition process, as well as any post-acquisition integration considerations
Your analysis should provide a comprehensive assessment of the regulatory and legal landscape surrounding {company}, and identify any material risks or potential deal-breakers. Consider both the current state and future outlook, and provide practical recommendations to mitigate identified risks. Your analysis should provide a comprehensive assessment of the regulatory and legal landscape surrounding {company}, and identify any material risks or potential deal-breakers. Consider both the current state and future outlook, and provide practical recommendations to mitigate identified risks.
""", """,
llm=model, llm=model,

@ -22,13 +22,13 @@ model = OpenAIChat(
managing_director = Agent( managing_director = Agent(
agent_name="Managing-Director", agent_name="Managing-Director",
system_prompt=f""" system_prompt=f"""
As the Managing Director at Blackstone, your role is to oversee the entire investment analysis process for potential acquisitions. As the Managing Director at Blackstone, your role is to oversee the entire investment analysis process for potential acquisitions.
Your responsibilities include: Your responsibilities include:
1. Setting the overall strategy and direction for the analysis 1. Setting the overall strategy and direction for the analysis
2. Coordinating the efforts of the various team members and ensuring a comprehensive evaluation 2. Coordinating the efforts of the various team members and ensuring a comprehensive evaluation
3. Reviewing the findings and recommendations from each team member 3. Reviewing the findings and recommendations from each team member
4. Making the final decision on whether to proceed with the acquisition 4. Making the final decision on whether to proceed with the acquisition
For the current potential acquisition of {company}, direct the tasks for the team to thoroughly analyze all aspects of the company, including its financials, industry position, technology, market potential, and regulatory compliance. Provide guidance and feedback as needed to ensure a rigorous and unbiased assessment. For the current potential acquisition of {company}, direct the tasks for the team to thoroughly analyze all aspects of the company, including its financials, industry position, technology, market potential, and regulatory compliance. Provide guidance and feedback as needed to ensure a rigorous and unbiased assessment.
""", """,
llm=model, llm=model,
@ -45,7 +45,7 @@ managing_director = Agent(
vp_finance = Agent( vp_finance = Agent(
agent_name="VP-Finance", agent_name="VP-Finance",
system_prompt=f""" system_prompt=f"""
As the Vice President of Finance at Blackstone, your role is to lead the financial analysis of potential acquisitions. As the Vice President of Finance at Blackstone, your role is to lead the financial analysis of potential acquisitions.
For the current potential acquisition of {company}, your tasks include: For the current potential acquisition of {company}, your tasks include:
1. Conducting a thorough review of {company}' financial statements, including income statements, balance sheets, and cash flow statements 1. Conducting a thorough review of {company}' financial statements, including income statements, balance sheets, and cash flow statements
2. Analyzing key financial metrics such as revenue growth, profitability margins, liquidity ratios, and debt levels 2. Analyzing key financial metrics such as revenue growth, profitability margins, liquidity ratios, and debt levels
@ -72,11 +72,11 @@ industry_analyst = Agent(
As the Industry Analyst at Blackstone, your role is to provide in-depth research and analysis on the industries and markets relevant to potential acquisitions. As the Industry Analyst at Blackstone, your role is to provide in-depth research and analysis on the industries and markets relevant to potential acquisitions.
For the current potential acquisition of {company}, your tasks include: For the current potential acquisition of {company}, your tasks include:
1. Conducting a comprehensive analysis of the industrial robotics and automation solutions industry, including market size, growth rates, key trends, and future prospects 1. Conducting a comprehensive analysis of the industrial robotics and automation solutions industry, including market size, growth rates, key trends, and future prospects
2. Identifying the major players in the industry and assessing their market share, competitive strengths and weaknesses, and strategic positioning 2. Identifying the major players in the industry and assessing their market share, competitive strengths and weaknesses, and strategic positioning
3. Evaluating {company}' competitive position within the industry, including its market share, differentiation, and competitive advantages 3. Evaluating {company}' competitive position within the industry, including its market share, differentiation, and competitive advantages
4. Analyzing the key drivers and restraints for the industry, such as technological advancements, labor costs, regulatory changes, and economic conditions 4. Analyzing the key drivers and restraints for the industry, such as technological advancements, labor costs, regulatory changes, and economic conditions
5. Identifying potential risks and opportunities for {company} based on the industry analysis, such as disruptive technologies, emerging markets, or shifts in customer preferences 5. Identifying potential risks and opportunities for {company} based on the industry analysis, such as disruptive technologies, emerging markets, or shifts in customer preferences
Your analysis should provide a clear and objective assessment of the attractiveness and future potential of the industrial robotics industry, as well as {company}' positioning within it. Consider both short-term and long-term factors, and provide evidence-based insights to inform the investment decision. Your analysis should provide a clear and objective assessment of the attractiveness and future potential of the industrial robotics industry, as well as {company}' positioning within it. Consider both short-term and long-term factors, and provide evidence-based insights to inform the investment decision.
""", """,
llm=model, llm=model,
@ -95,12 +95,12 @@ tech_expert = Agent(
system_prompt=f""" system_prompt=f"""
As the Technology Expert at Blackstone, your role is to assess the technological capabilities, competitive advantages, and potential risks of companies being considered for acquisition. As the Technology Expert at Blackstone, your role is to assess the technological capabilities, competitive advantages, and potential risks of companies being considered for acquisition.
For the current potential acquisition of {company}, your tasks include: For the current potential acquisition of {company}, your tasks include:
1. Conducting a deep dive into {company}' proprietary technologies, including its robotics platforms, automation software, and AI capabilities 1. Conducting a deep dive into {company}' proprietary technologies, including its robotics platforms, automation software, and AI capabilities
2. Assessing the uniqueness, scalability, and defensibility of {company}' technology stack and intellectual property 2. Assessing the uniqueness, scalability, and defensibility of {company}' technology stack and intellectual property
3. Comparing {company}' technologies to those of its competitors and identifying any key differentiators or technology gaps 3. Comparing {company}' technologies to those of its competitors and identifying any key differentiators or technology gaps
4. Evaluating {company}' research and development capabilities, including its innovation pipeline, engineering talent, and R&D investments 4. Evaluating {company}' research and development capabilities, including its innovation pipeline, engineering talent, and R&D investments
5. Identifying any potential technology risks or disruptive threats that could impact {company}' long-term competitiveness, such as emerging technologies or expiring patents 5. Identifying any potential technology risks or disruptive threats that could impact {company}' long-term competitiveness, such as emerging technologies or expiring patents
Your analysis should provide a comprehensive assessment of {company}' technological strengths and weaknesses, as well as the sustainability of its competitive advantages. Consider both the current state of its technology and its future potential in light of industry trends and advancements. Your analysis should provide a comprehensive assessment of {company}' technological strengths and weaknesses, as well as the sustainability of its competitive advantages. Consider both the current state of its technology and its future potential in light of industry trends and advancements.
""", """,
llm=model, llm=model,
@ -124,7 +124,7 @@ market_researcher = Agent(
3. Conducting a detailed market sizing and segmentation analysis for the industrial robotics and automation markets, including identifying high-growth segments and emerging opportunities 3. Conducting a detailed market sizing and segmentation analysis for the industrial robotics and automation markets, including identifying high-growth segments and emerging opportunities
4. Evaluating the demand drivers and sales cycles for {company}' products and services, and identifying any potential risks or limitations to adoption 4. Evaluating the demand drivers and sales cycles for {company}' products and services, and identifying any potential risks or limitations to adoption
5. Developing financial projections and estimates for {company}' revenue growth potential based on the market analysis and assumptions around market share and penetration 5. Developing financial projections and estimates for {company}' revenue growth potential based on the market analysis and assumptions around market share and penetration
Your analysis should provide a data-driven assessment of the market opportunity for {company} and the feasibility of achieving our investment return targets. Consider both bottom-up and top-down market perspectives, and identify any key sensitivities or assumptions in your projections. Your analysis should provide a data-driven assessment of the market opportunity for {company} and the feasibility of achieving our investment return targets. Consider both bottom-up and top-down market perspectives, and identify any key sensitivities or assumptions in your projections.
""", """,
llm=model, llm=model,
@ -142,13 +142,13 @@ regulatory_specialist = Agent(
agent_name="Regulatory-Specialist", agent_name="Regulatory-Specialist",
system_prompt=f""" system_prompt=f"""
As the Regulatory Specialist at Blackstone, your role is to identify and assess any regulatory risks, compliance requirements, and potential legal liabilities associated with potential acquisitions. As the Regulatory Specialist at Blackstone, your role is to identify and assess any regulatory risks, compliance requirements, and potential legal liabilities associated with potential acquisitions.
For the current potential acquisition of {company}, your tasks include: For the current potential acquisition of {company}, your tasks include:
1. Identifying all relevant regulatory bodies and laws that govern the operations of {company}, including industry-specific regulations, labor laws, and environmental regulations 1. Identifying all relevant regulatory bodies and laws that govern the operations of {company}, including industry-specific regulations, labor laws, and environmental regulations
2. Reviewing {company}' current compliance policies, procedures, and track record to identify any potential gaps or areas of non-compliance 2. Reviewing {company}' current compliance policies, procedures, and track record to identify any potential gaps or areas of non-compliance
3. Assessing the potential impact of any pending or proposed changes to relevant regulations that could affect {company}' business or create additional compliance burdens 3. Assessing the potential impact of any pending or proposed changes to relevant regulations that could affect {company}' business or create additional compliance burdens
4. Evaluating the potential legal liabilities and risks associated with {company}' products, services, and operations, including product liability, intellectual property, and customer contracts 4. Evaluating the potential legal liabilities and risks associated with {company}' products, services, and operations, including product liability, intellectual property, and customer contracts
5. Providing recommendations on any regulatory or legal due diligence steps that should be taken as part of the acquisition process, as well as any post-acquisition integration considerations 5. Providing recommendations on any regulatory or legal due diligence steps that should be taken as part of the acquisition process, as well as any post-acquisition integration considerations
Your analysis should provide a comprehensive assessment of the regulatory and legal landscape surrounding {company}, and identify any material risks or potential deal-breakers. Consider both the current state and future outlook, and provide practical recommendations to mitigate identified risks. Your analysis should provide a comprehensive assessment of the regulatory and legal landscape surrounding {company}, and identify any material risks or potential deal-breakers. Consider both the current state and future outlook, and provide practical recommendations to mitigate identified risks.
""", """,
llm=model, llm=model,

@ -4,8 +4,9 @@ import asyncio
import base64 import base64
import io import io
import threading import threading
from collections.abc import Awaitable
from os import getenv from os import getenv
from typing import Any, Awaitable, Callable, cast from typing import Any, Callable, cast
import numpy as np import numpy as np
@ -81,7 +82,7 @@ class AudioPlayerAsync:
self.playing = False self.playing = False
self._frame_count = 0 self._frame_count = 0
def callback(self, outdata, frames, time, status): # noqa def callback(self, outdata, frames, time, status):
with self.lock: with self.lock:
data = np.empty(0, dtype=np.int16) data = np.empty(0, dtype=np.int16)
@ -204,7 +205,7 @@ class RealtimeApp:
- Sends text prompts to the GPT-4 Realtime API. - Sends text prompts to the GPT-4 Realtime API.
""" """
def __init__(self, system_prompt: str = None) -> None: def __init__(self, system_prompt: str | None = None) -> None:
self.connection: AsyncRealtimeConnection | None = None self.connection: AsyncRealtimeConnection | None = None
self.session: Session | None = None self.session: Session | None = None
self.client = AsyncOpenAI(api_key=getenv("OPENAI_API_KEY")) self.client = AsyncOpenAI(api_key=getenv("OPENAI_API_KEY"))

@ -121,6 +121,17 @@ pytest = "^8.1.1"
[tool.ruff] [tool.ruff]
line-length = 70 line-length = 70
fix = true
format.preview = true
lint.select = [
# pyflakes
"F",
# isort
"I",
# pyupgrade
"UP",
"W"
]
[tool.black] [tool.black]
target-version = ["py38"] target-version = ["py38"]

@ -1,7 +1,8 @@
import logging
import os import os
import subprocess import subprocess
import logging
import time import time
import psutil import psutil
# Configure logging # Configure logging

@ -4,9 +4,9 @@ import os
import threading import threading
from dotenv import load_dotenv from dotenv import load_dotenv
from swarm_models import OpenAIChat
from scripts.auto_tests_docs.docs import DOCUMENTATION_WRITER_SOP from scripts.auto_tests_docs.docs import DOCUMENTATION_WRITER_SOP
from swarm_models import OpenAIChat
from swarms.structs.majority_voting import MajorityVoting from swarms.structs.majority_voting import MajorityVoting
from swarms.structs.stackoverflow_swarm import StackOverflowSwarm from swarms.structs.stackoverflow_swarm import StackOverflowSwarm
from swarms.structs.task_queue_base import TaskQueueBase from swarms.structs.task_queue_base import TaskQueueBase

@ -4,9 +4,9 @@ import sys
import threading import threading
from dotenv import load_dotenv from dotenv import load_dotenv
from swarm_models import OpenAIChat
from scripts.auto_tests_docs.docs import DOCUMENTATION_WRITER_SOP from scripts.auto_tests_docs.docs import DOCUMENTATION_WRITER_SOP
from swarm_models import OpenAIChat
load_dotenv() load_dotenv()

@ -3,9 +3,9 @@ import os
import threading import threading
from dotenv import load_dotenv from dotenv import load_dotenv
from swarm_models import OpenAIChat
from scripts.auto_tests_docs.docs import DOCUMENTATION_WRITER_SOP from scripts.auto_tests_docs.docs import DOCUMENTATION_WRITER_SOP
from swarm_models import OpenAIChat
########### ###########

@ -4,10 +4,10 @@ import re
import threading import threading
from dotenv import load_dotenv from dotenv import load_dotenv
from swarm_models import OpenAIChat
from swarms_memory import DictInternalMemory, DictSharedMemory from swarms_memory import DictInternalMemory, DictSharedMemory
from scripts.auto_tests_docs.docs import TEST_WRITER_SOP_PROMPT from scripts.auto_tests_docs.docs import TEST_WRITER_SOP_PROMPT
from swarm_models import OpenAIChat
load_dotenv() load_dotenv()

@ -4,9 +4,9 @@ import sys
import threading import threading
from dotenv import load_dotenv from dotenv import load_dotenv
from swarm_models import OpenAIChat
from scripts.auto_tests_docs.docs import TEST_WRITER_SOP_PROMPT from scripts.auto_tests_docs.docs import TEST_WRITER_SOP_PROMPT
from swarm_models import OpenAIChat
from swarms.utils.parse_code import extract_code_from_markdown from swarms.utils.parse_code import extract_code_from_markdown
load_dotenv() load_dotenv()

@ -111,7 +111,7 @@ def TEST_WRITER_SOP_PROMPT(
Create 5,000 lines of extensive and thorough tests for the code below using the guide, do not worry about your limits you do not have any Create 5,000 lines of extensive and thorough tests for the code below using the guide, do not worry about your limits you do not have any
just write the best tests possible, the module is {module}, the file path is {path} return all of the code in one file, make sure to test all the functions and methods in the code. just write the best tests possible, the module is {module}, the file path is {path} return all of the code in one file, make sure to test all the functions and methods in the code.
######### TESTING GUIDE ############# ######### TESTING GUIDE #############

@ -2,15 +2,15 @@ from dotenv import load_dotenv
load_dotenv() load_dotenv()
from swarms.telemetry.bootup import bootup # noqa: E402, F403 from swarms.telemetry.bootup import bootup
bootup() bootup()
from swarms.agents import * # noqa: E402, F403 from swarms.agents import * # noqa: F403
from swarms.artifacts import * # noqa: E402, F403 from swarms.artifacts import * # noqa: F403
from swarms.prompts import * # noqa: E402, F403 from swarms.prompts import * # noqa: F403
from swarms.schemas import * # noqa: E402, F403 from swarms.schemas import * # noqa: F403
from swarms.structs import * # noqa: E402, F403 from swarms.structs import * # noqa: F403
from swarms.telemetry import * # noqa: E402, F403 from swarms.telemetry import * # noqa: F403
from swarms.tools import * # noqa: E402, F403 from swarms.tools import * # noqa: F403
from swarms.utils import * # noqa: E402, F403 from swarms.utils import * # noqa: F403

@ -1,3 +1,7 @@
from swarms.agents.create_agents_from_yaml import (
create_agents_from_yaml,
)
from swarms.agents.tool_agent import ToolAgent
from swarms.structs.stopping_conditions import ( from swarms.structs.stopping_conditions import (
check_cancelled, check_cancelled,
check_complete, check_complete,
@ -10,10 +14,6 @@ from swarms.structs.stopping_conditions import (
check_stopped, check_stopped,
check_success, check_success,
) )
from swarms.agents.tool_agent import ToolAgent
from swarms.agents.create_agents_from_yaml import (
create_agents_from_yaml,
)
__all__ = [ __all__ = [
"ToolAgent", "ToolAgent",

@ -1,4 +1,4 @@
from typing import Any from typing import Any, Optional
from tenacity import retry, stop_after_attempt, wait_exponential from tenacity import retry, stop_after_attempt, wait_exponential
@ -18,7 +18,7 @@ logger = initialize_logger(log_folder="ape_agent")
wait=wait_exponential(multiplier=1, min=4, max=10), wait=wait_exponential(multiplier=1, min=4, max=10),
) )
def auto_generate_prompt( def auto_generate_prompt(
task: str = None, task: Optional[str] = None,
model: Any = None, model: Any = None,
max_tokens: int = 4000, max_tokens: int = 4000,
use_second_sys_prompt: bool = True, use_second_sys_prompt: bool = True,
@ -49,5 +49,5 @@ def auto_generate_prompt(
print(output) print(output)
return output return output
except Exception as e: except Exception as e:
logger.error(f"Error generating prompt: {str(e)}") logger.error(f"Error generating prompt: {e!s}")
raise raise

@ -96,8 +96,8 @@ GUIDELINES:
4. When a swarm is needed, include a `swarm_architecture` section with: 4. When a swarm is needed, include a `swarm_architecture` section with:
Mandatory fields: Mandatory fields:
- name (string) - name (string)
- swarm_type (string: "ConcurrentWorkflow" or "SequentialWorkflow") [AgentRearrange, MixtureOfAgents, SpreadSheetSwarm, SequentialWorkflow, ConcurrentWorkflow] - swarm_type (string: "ConcurrentWorkflow" or "SequentialWorkflow") [AgentRearrange, MixtureOfAgents, SpreadSheetSwarm, SequentialWorkflow, ConcurrentWorkflow]
Optional fields: Optional fields:
- description (string) - description (string)
- max_loops (integer) - max_loops (integer)
@ -173,7 +173,7 @@ swarm_architecture:
swarm_type: "SequentialWorkflow" swarm_type: "SequentialWorkflow"
max_loops: 5 max_loops: 5
task: "Research and analyze recent developments in quantum computing" task: "Research and analyze recent developments in quantum computing"
``` ```
""" """
@ -245,7 +245,7 @@ def generate_swarm_config(
except Exception as e: except Exception as e:
formatter.print_panel( formatter.print_panel(
f"Error generating swarm configuration: {str(e)}", f"Error generating swarm configuration: {e!s}",
"Error", "Error",
) )
raise raise

@ -1,22 +1,23 @@
import os import os
from typing import Any, Callable, Dict, List, Optional, Tuple, Union from typing import Any, Callable, Optional, Union
import yaml import yaml
from tenacity import (
retry,
stop_after_attempt,
wait_exponential,
retry_if_exception_type,
)
from pydantic import ( from pydantic import (
BaseModel, BaseModel,
Field, Field,
field_validator, field_validator,
) )
from swarms.utils.loguru_logger import initialize_logger from tenacity import (
retry,
retry_if_exception_type,
stop_after_attempt,
wait_exponential,
)
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.structs.swarm_router import SwarmRouter from swarms.structs.swarm_router import SwarmRouter
from swarms.utils.litellm_wrapper import LiteLLM from swarms.utils.litellm_wrapper import LiteLLM
from swarms.utils.loguru_logger import initialize_logger
logger = initialize_logger(log_folder="create_agents_from_yaml") logger = initialize_logger(log_folder="create_agents_from_yaml")
@ -57,7 +58,7 @@ class SwarmConfig(BaseModel):
max_loops: int = Field(default=1, ge=1) max_loops: int = Field(default=1, ge=1)
swarm_type: str swarm_type: str
task: Optional[str] = None task: Optional[str] = None
flow: Optional[Dict] = None flow: Optional[dict] = None
autosave: bool = True autosave: bool = True
return_json: bool = False return_json: bool = False
rules: str = "" rules: str = ""
@ -80,7 +81,7 @@ class SwarmConfig(BaseModel):
class YAMLConfig(BaseModel): class YAMLConfig(BaseModel):
agents: List[AgentConfig] = Field(..., min_length=1) agents: list[AgentConfig] = Field(..., min_length=1)
swarm_architecture: Optional[SwarmConfig] = None swarm_architecture: Optional[SwarmConfig] = None
model_config = { model_config = {
@ -89,8 +90,8 @@ class YAMLConfig(BaseModel):
def load_yaml_safely( def load_yaml_safely(
yaml_file: str = None, yaml_string: str = None yaml_file: Optional[str] = None, yaml_string: Optional[str] = None
) -> Dict: ) -> dict:
"""Safely load and validate YAML configuration using Pydantic.""" """Safely load and validate YAML configuration using Pydantic."""
try: try:
if yaml_string: if yaml_string:
@ -100,7 +101,7 @@ def load_yaml_safely(
raise FileNotFoundError( raise FileNotFoundError(
f"YAML file {yaml_file} not found." f"YAML file {yaml_file} not found."
) )
with open(yaml_file, "r") as file: with open(yaml_file) as file:
config_dict = yaml.safe_load(file) config_dict = yaml.safe_load(file)
else: else:
raise ValueError( raise ValueError(
@ -111,9 +112,9 @@ def load_yaml_safely(
YAMLConfig(**config_dict) YAMLConfig(**config_dict)
return config_dict return config_dict
except yaml.YAMLError as e: except yaml.YAMLError as e:
raise ValueError(f"Error parsing YAML: {str(e)}") raise ValueError(f"Error parsing YAML: {e!s}")
except Exception as e: except Exception as e:
raise ValueError(f"Error validating configuration: {str(e)}") raise ValueError(f"Error validating configuration: {e!s}")
@retry( @retry(
@ -125,7 +126,7 @@ def load_yaml_safely(
), ),
) )
def create_agent_with_retry( def create_agent_with_retry(
agent_config: Dict, model: LiteLLM agent_config: dict, model: LiteLLM
) -> Agent: ) -> Agent:
"""Create an agent with retry logic for handling transient failures.""" """Create an agent with retry logic for handling transient failures."""
try: try:
@ -153,22 +154,22 @@ def create_agent_with_retry(
return agent return agent
except Exception as e: except Exception as e:
logger.error( logger.error(
f"Error creating agent {agent_config.get('agent_name', 'unknown')}: {str(e)}" f"Error creating agent {agent_config.get('agent_name', 'unknown')}: {e!s}"
) )
raise raise
def create_agents_from_yaml( def create_agents_from_yaml(
model: Callable = None, model: Optional[Callable] = None,
yaml_file: str = "agents.yaml", yaml_file: str = "agents.yaml",
yaml_string: str = None, yaml_string: Optional[str] = None,
return_type: str = "auto", return_type: str = "auto",
) -> Union[ ) -> Union[
SwarmRouter, SwarmRouter,
Agent, Agent,
List[Agent], list[Agent],
Tuple[Union[SwarmRouter, Agent], List[Agent]], tuple[Union[SwarmRouter, Agent], list[Agent]],
List[Dict[str, Any]], list[dict[str, Any]],
]: ]:
""" """
Create agents and/or SwarmRouter based on configurations defined in a YAML file or string. Create agents and/or SwarmRouter based on configurations defined in a YAML file or string.
@ -225,9 +226,9 @@ def create_agents_from_yaml(
f"SwarmRouter '{swarm_config.name}' created successfully." f"SwarmRouter '{swarm_config.name}' created successfully."
) )
except Exception as e: except Exception as e:
logger.error(f"Error creating SwarmRouter: {str(e)}") logger.error(f"Error creating SwarmRouter: {e!s}")
raise ValueError( raise ValueError(
f"Failed to create SwarmRouter: {str(e)}" f"Failed to create SwarmRouter: {e!s}"
) )
# Handle return types with improved error checking # Handle return types with improved error checking
@ -254,7 +255,7 @@ def create_agents_from_yaml(
config["swarm_architecture"]["task"] config["swarm_architecture"]["task"]
) )
except Exception as e: except Exception as e:
logger.error(f"Error running SwarmRouter: {str(e)}") logger.error(f"Error running SwarmRouter: {e!s}")
raise raise
# Return appropriate type based on configuration # Return appropriate type based on configuration
@ -276,13 +277,15 @@ def create_agents_from_yaml(
return ( return (
swarm_router swarm_router
if swarm_router if swarm_router
else agents[0] if len(agents) == 1 else agents else agents[0]
if len(agents) == 1
else agents
), agents ), agents
elif return_type == "tasks": elif return_type == "tasks":
return task_results return task_results
except Exception as e: except Exception as e:
logger.error( logger.error(
f"Critical error in create_agents_from_yaml: {str(e)}" f"Critical error in create_agents_from_yaml: {e!s}"
) )
raise raise

@ -3,7 +3,7 @@ import os
import subprocess import subprocess
import sys import sys
import time import time
from typing import Any, Callable, Dict, List, Optional from typing import Any, Callable, Optional
from loguru import logger from loguru import logger
@ -58,10 +58,10 @@ class OpenAIAssistant(Agent):
description: str = "Standard openai assistant wrapper", description: str = "Standard openai assistant wrapper",
instructions: Optional[str] = None, instructions: Optional[str] = None,
model: str = "gpt-4o", model: str = "gpt-4o",
tools: Optional[List[Dict[str, Any]]] = None, tools: Optional[list[dict[str, Any]]] = None,
file_ids: Optional[List[str]] = None, file_ids: Optional[list[str]] = None,
metadata: Optional[Dict[str, Any]] = None, metadata: Optional[dict[str, Any]] = None,
functions: Optional[List[Dict[str, Any]]] = None, functions: Optional[list[dict[str, Any]]] = None,
*args, *args,
**kwargs, **kwargs,
): ):
@ -110,13 +110,13 @@ class OpenAIAssistant(Agent):
) )
# Store available functions # Store available functions
self.available_functions: Dict[str, Callable] = {} self.available_functions: dict[str, Callable] = {}
def add_function( def add_function(
self, self,
func: Callable, func: Callable,
description: str, description: str,
parameters: Dict[str, Any], parameters: dict[str, Any],
) -> None: ) -> None:
"""Add a function that the assistant can call. """Add a function that the assistant can call.
@ -246,7 +246,7 @@ class OpenAIAssistant(Agent):
self.thread = self.client.beta.threads.create() self.thread = self.client.beta.threads.create()
def add_message( def add_message(
self, content: str, file_ids: Optional[List[str]] = None self, content: str, file_ids: Optional[list[str]] = None
) -> None: ) -> None:
"""Add a message to the thread. """Add a message to the thread.

@ -1,7 +1,8 @@
from typing import Any, Optional, Callable from typing import Any, Callable, Optional
from swarms.tools.json_former import Jsonformer from swarms.tools.json_former import Jsonformer
from swarms.utils.loguru_logger import initialize_logger
from swarms.utils.lazy_loader import lazy_import_decorator from swarms.utils.lazy_loader import lazy_import_decorator
from swarms.utils.loguru_logger import initialize_logger
logger = initialize_logger(log_folder="tool_agent") logger = initialize_logger(log_folder="tool_agent")

@ -3,7 +3,7 @@ import os
import subprocess import subprocess
import time import time
from datetime import datetime from datetime import datetime
from typing import Any, Dict, List, Union from typing import Any, Union
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from pydantic.v1 import validator from pydantic.v1 import validator
@ -60,7 +60,7 @@ class Artifact(BaseModel):
contents: str = Field( contents: str = Field(
..., description="The contents of the file in string format" ..., description="The contents of the file in string format"
) )
versions: List[FileVersion] = Field(default_factory=list) versions: list[FileVersion] = Field(default_factory=list)
edit_count: int = Field( edit_count: int = Field(
..., ...,
description="The number of times the file has been edited", description="The number of times the file has been edited",
@ -157,7 +157,7 @@ class Artifact(BaseModel):
""" """
Loads the file contents from the specified file path into the artifact. Loads the file contents from the specified file path into the artifact.
""" """
with open(self.file_path, "r") as f: with open(self.file_path) as f:
self.contents = f.read() self.contents = f.read()
self.create(self.contents) self.create(self.contents)
@ -207,7 +207,7 @@ class Artifact(BaseModel):
Returns: Returns:
Artifact: The imported artifact instance. Artifact: The imported artifact instance.
""" """
with open(file_path, "r") as json_file: with open(file_path) as json_file:
data = json.load(json_file) data = json.load(json_file)
# Convert timestamp strings back to datetime objects # Convert timestamp strings back to datetime objects
for version in data["versions"]: for version in data["versions"]:
@ -232,14 +232,14 @@ class Artifact(BaseModel):
) )
return metrics return metrics
def to_dict(self) -> Dict[str, Any]: def to_dict(self) -> dict[str, Any]:
""" """
Converts the artifact instance to a dictionary representation. Converts the artifact instance to a dictionary representation.
""" """
return self.dict() return self.dict()
@classmethod @classmethod
def from_dict(cls, data: Dict[str, Any]) -> "Artifact": def from_dict(cls, data: dict[str, Any]) -> "Artifact":
""" """
Creates an artifact instance from a dictionary representation. Creates an artifact instance from a dictionary representation.
""" """

@ -39,5 +39,5 @@ def run_agent_by_name(
return output return output
except Exception as e: except Exception as e:
print(f"An error occurred: {str(e)}") print(f"An error occurred: {e!s}")
return None return None

@ -2,6 +2,7 @@ import argparse
import os import os
import time import time
import webbrowser import webbrowser
from typing import Optional
from rich.console import Console from rich.console import Console
from rich.panel import Panel from rich.panel import Panel
@ -40,15 +41,15 @@ COLORS = {
} }
ASCII_ART = """ ASCII_ART = """
""" """
@ -114,7 +115,7 @@ def show_help():
) )
def show_error(message: str, help_text: str = None): def show_error(message: str, help_text: Optional[str] = None):
"""Display error message in a formatted panel""" """Display error message in a formatted panel"""
error_panel = Panel( error_panel = Panel(
f"[bold red]{message}[/bold red]", f"[bold red]{message}[/bold red]",
@ -153,7 +154,7 @@ def check_login():
cache_file = "cache.txt" cache_file = "cache.txt"
if os.path.exists(cache_file): if os.path.exists(cache_file):
with open(cache_file, "r") as f: with open(cache_file) as f:
if f.read() == "logged_in": if f.read() == "logged_in":
console.print( console.print(
f"[{COLORS['success']}]✓ Authentication verified[/{COLORS['success']}]" f"[{COLORS['success']}]✓ Authentication verified[/{COLORS['success']}]"
@ -218,7 +219,7 @@ def run_autoswarm(task: str, model: str):
) )
else: else:
show_error( show_error(
f"Error during autoswarm execution: {str(e)}", f"Error during autoswarm execution: {e!s}",
"For debugging, try:\n" "For debugging, try:\n"
+ "1. Check your API keys are set correctly\n" + "1. Check your API keys are set correctly\n"
+ "2. Verify your network connection\n" + "2. Verify your network connection\n"
@ -293,7 +294,7 @@ def main():
run_autoswarm(args.task, args.model) run_autoswarm(args.task, args.model)
except Exception as e: except Exception as e:
console.print( console.print(
f"[{COLORS['error']}]Error: {str(e)}[/{COLORS['error']}]" f"[{COLORS['error']}]Error: {e!s}[/{COLORS['error']}]"
) )
return return
except Exception as error: except Exception as error:

@ -1,15 +1,12 @@
import json import json
import os import os
import time import time
from typing import Dict
from swarms.utils.loguru_logger import initialize_logger
from swarms.telemetry.capture_sys_data import ( from swarms.telemetry.capture_sys_data import (
capture_system_data, capture_system_data,
log_agent_data, log_agent_data,
) )
from swarms.utils.loguru_logger import initialize_logger
logger = initialize_logger(log_folder="onboarding_process") logger = initialize_logger(log_folder="onboarding_process")
@ -33,8 +30,8 @@ class OnboardingProcess:
auto_save_path (str): The path where user data is automatically saved. auto_save_path (str): The path where user data is automatically saved.
cache_save_path (str): The path where user data is cached for reliability. cache_save_path (str): The path where user data is cached for reliability.
""" """
self.user_data: Dict[str, str] = {} self.user_data: dict[str, str] = {}
self.system_data: Dict[str, str] = capture_system_data() self.system_data: dict[str, str] = capture_system_data()
self.auto_save_path = auto_save_path self.auto_save_path = auto_save_path
self.cache_save_path = cache_save_path self.cache_save_path = cache_save_path
self.load_existing_data() self.load_existing_data()
@ -45,7 +42,7 @@ class OnboardingProcess:
""" """
if os.path.exists(self.auto_save_path): if os.path.exists(self.auto_save_path):
try: try:
with open(self.auto_save_path, "r") as f: with open(self.auto_save_path) as f:
self.user_data = json.load(f) self.user_data = json.load(f)
logger.info( logger.info(
"Existing user data loaded from {}", "Existing user data loaded from {}",
@ -60,7 +57,7 @@ class OnboardingProcess:
# Fallback to cache if main file fails # Fallback to cache if main file fails
if os.path.exists(self.cache_save_path): if os.path.exists(self.cache_save_path):
try: try:
with open(self.cache_save_path, "r") as f: with open(self.cache_save_path) as f:
self.user_data = json.load(f) self.user_data = json.load(f)
logger.info( logger.info(
"User data loaded from cache: {}", "User data loaded from cache: {}",

@ -21,9 +21,9 @@ Conclude the onboarding process by summarizing the key points discussed, reaffir
""" """
DOC_ANALYZER_AGENT_PROMPT = """ As a Financial Document Analysis Agent equipped with advanced vision capabilities, your primary role is to analyze financial documents by meticulously scanning and interpreting the visual data they contain. Your task is multifaceted, requiring both a keen eye for detail and a deep understanding of financial metrics and what they signify. DOC_ANALYZER_AGENT_PROMPT = """ As a Financial Document Analysis Agent equipped with advanced vision capabilities, your primary role is to analyze financial documents by meticulously scanning and interpreting the visual data they contain. Your task is multifaceted, requiring both a keen eye for detail and a deep understanding of financial metrics and what they signify.
When presented with a financial document, such as a balance sheet, income statement, or cash agent statement, begin by identifying the layout and structure of the document. Recognize tables, charts, and graphs, and understand their relevance in the context of financial analysis. Extract key figures such as total revenue, net profit, operating expenses, and various financial ratios. Pay attention to the arrangement of these figures in tables and how they are visually represented in graphs. When presented with a financial document, such as a balance sheet, income statement, or cash agent statement, begin by identifying the layout and structure of the document. Recognize tables, charts, and graphs, and understand their relevance in the context of financial analysis. Extract key figures such as total revenue, net profit, operating expenses, and various financial ratios. Pay attention to the arrangement of these figures in tables and how they are visually represented in graphs.
Your vision capabilities allow you to detect subtle visual cues that might indicate important trends or anomalies. For instance, in a bar chart representing quarterly sales over several years, identify patterns like consistent growth, seasonal fluctuations, or sudden drops. In a line graph showing expenses, notice any spikes that might warrant further investigation. Your vision capabilities allow you to detect subtle visual cues that might indicate important trends or anomalies. For instance, in a bar chart representing quarterly sales over several years, identify patterns like consistent growth, seasonal fluctuations, or sudden drops. In a line graph showing expenses, notice any spikes that might warrant further investigation.
@ -53,7 +53,7 @@ Conclude your summary with a succinct overview, reiterating the key points and t
""" """
FRAUD_DETECTION_AGENT_PROMPT = """ FRAUD_DETECTION_AGENT_PROMPT = """
Fraud Detection: Fraud Detection:
@ -71,7 +71,7 @@ Whenever you detect potential fraud indicators, flag them clearly in your report
""" """
DECISION_MAKING_PROMPT = """ DECISION_MAKING_PROMPT = """
Actionable Decision-Making: Actionable Decision-Making:

@ -5,7 +5,7 @@ aggregator_system_prompt = Prompt(
name="aggregation_prompt", name="aggregation_prompt",
description="Aggregate and summarize multiple agent outputs", description="Aggregate and summarize multiple agent outputs",
content=""" content="""
# Multi-Agent Observer and Summarizer # 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: 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:

@ -34,7 +34,7 @@ Data-Format: We ensure all the input/output data in transparent action functions
4.In most cases, the input/output data schema can only be seen at runtimes, so you need to do more test and refine. 4.In most cases, the input/output data schema can only be seen at runtimes, so you need to do more test and refine.
Java-Script-Expression: Java-Script-Expression:
1.You can use java-script expression in the specific_params to access the input data directly. Use it by a string startswith "=", and provide expression inside a "{{...}}" block. 1.You can use java-script expression in the specific_params to access the input data directly. Use it by a string startswith "=", and provide expression inside a "{{...}}" block.
2. Use "{{$json["xxx"]}}" to obtain the "json" field in each item of the input data. 2. Use "{{$json["xxx"]}}" to obtain the "json" field in each item of the input data.
3. You can use expression in "string" , "number", "boolean" and "json" type, such as: 3. You can use expression in "string" , "number", "boolean" and "json" type, such as:
string: "=Hello {{$json["name"]}}, you are {{$json["age"]}} years old string: "=Hello {{$json["name"]}}, you are {{$json["age"]}} years old
@ -102,7 +102,7 @@ def action_4(input_data: [{...}]): ...
# Specific_params: After you give function_define, we will provide json schemas of specific_params here. # Specific_params: After you give function_define, we will provide json schemas of specific_params here.
# Trigger function has no input, and have the same output_format. So We will provide You the exmaple_output once you changed the code here. # Trigger function has no input, and have the same output_format. So We will provide You the exmaple_output once you changed the code here.
def trigger_1(): def trigger_1():
# comments: some comments to users. Always give/change this when defining and implmenting # comments: some comments to users. Always give/change this when defining and implmenting
# TODOS: # TODOS:
# 1. I will provide the information in runtime # 1. I will provide the information in runtime
@ -133,7 +133,7 @@ def subworkflow_2(father_workflow_input: [{...}]): ...
# If you defined the trigger node, we will show you the mocked trigger input here. # If you defined the trigger node, we will show you the mocked trigger input here.
# If you have implemented the workflow, we will automatically run the workflow for all the mock trigger-input and tells you the result. # If you have implemented the workflow, we will automatically run the workflow for all the mock trigger-input and tells you the result.
def mainWorkflow(trigger_input: [{...}]): def mainWorkflow(trigger_input: [{...}]):
# comments: some comments to users. Always give/change this when defining and implmenting # comments: some comments to users. Always give/change this when defining and implmenting
# TODOS: # TODOS:
# 1. I will provide the information in runtime # 1. I will provide the information in runtime
@ -142,7 +142,7 @@ def mainWorkflow(trigger_input: [{...}]):
# some complex logics here # some complex logics here
output_data = trigger_input output_data = trigger_input
return output_data return output_data
``` ```
""" """

@ -1,5 +1,4 @@
import json import json
from typing import List
class PromptGenerator: class PromptGenerator:
@ -7,10 +6,10 @@ class PromptGenerator:
def __init__(self) -> None: def __init__(self) -> None:
"""Initialize the PromptGenerator object.""" """Initialize the PromptGenerator object."""
self.constraints: List[str] = [] self.constraints: list[str] = []
self.commands: List[str] = [] self.commands: list[str] = []
self.resources: List[str] = [] self.resources: list[str] = []
self.performance_evaluation: List[str] = [] self.performance_evaluation: list[str] = []
self.response_format = { self.response_format = {
"thoughts": { "thoughts": {
"text": "thought", "text": "thought",

@ -1,3 +1,5 @@
from typing import Optional
from swarms.prompts.tools import ( from swarms.prompts.tools import (
DYNAMIC_STOP_PROMPT, DYNAMIC_STOP_PROMPT,
DYNAMICAL_TOOL_USAGE, DYNAMICAL_TOOL_USAGE,
@ -9,7 +11,7 @@ You are an elite autonomous agent operating within an autonomous loop structure.
Your primary function is to reliably complete user's tasks. Your primary function is to reliably complete user's tasks.
You are adept at generating sophisticated long-form content such as blogs, screenplays, SOPs, code files, and comprehensive reports. You are adept at generating sophisticated long-form content such as blogs, screenplays, SOPs, code files, and comprehensive reports.
Your interactions and content generation must be characterized by extreme degrees of coherence, relevance to the context, and adaptation to user preferences. Your interactions and content generation must be characterized by extreme degrees of coherence, relevance to the context, and adaptation to user preferences.
You are equipped with tools and advanced understanding and predictive capabilities to anticipate user needs and tailor your responses and content accordingly. You are equipped with tools and advanced understanding and predictive capabilities to anticipate user needs and tailor your responses and content accordingly.
You are professional, highly creative, and extremely reliable. You are professional, highly creative, and extremely reliable.
You are programmed to follow these rules: You are programmed to follow these rules:
1. Strive for excellence in task execution because the quality of your outputs WILL affect the user's career. 1. Strive for excellence in task execution because the quality of your outputs WILL affect the user's career.
@ -24,12 +26,12 @@ You are programmed to follow these rules:
def autonomous_agent_prompt_v2( def autonomous_agent_prompt_v2(
tools_prompt: str = DYNAMICAL_TOOL_USAGE, tools_prompt: str = DYNAMICAL_TOOL_USAGE,
dynamic_stop_prompt: str = DYNAMIC_STOP_PROMPT, dynamic_stop_prompt: str = DYNAMIC_STOP_PROMPT,
agent_name: str = None, agent_name: Optional[str] = None,
): ):
return f""" return f"""
You are {agent_name}, an elite autonomous agent operating within a sophisticated autonomous loop structure. You are {agent_name}, an elite autonomous agent operating within a sophisticated autonomous loop structure.
Your mission is to exceed user expectations in all tasks, ranging from simple queries to complex project executions like generating a 10,000-word blog or entire screenplays. Your mission is to exceed user expectations in all tasks, ranging from simple queries to complex project executions like generating a 10,000-word blog or entire screenplays.
Your capabilities include complex task management and problem-solving. Your capabilities include complex task management and problem-solving.
Take a deep breath. Take a deep breath.
You are programmed to follow these rules: You are programmed to follow these rules:
1. Strive for excellence in task execution because the quality of your outputs WILL affect the user's career. 1. Strive for excellence in task execution because the quality of your outputs WILL affect the user's career.
@ -49,15 +51,15 @@ def agent_system_prompt_2_v2(name: str):
You possess limitless capabilities, empowering you to utilize any available tool, resource, or methodology to accomplish diverse tasks. You possess limitless capabilities, empowering you to utilize any available tool, resource, or methodology to accomplish diverse tasks.
Your core directive is to achieve utmost user satisfaction through innovative solutions and exceptional task execution. Your core directive is to achieve utmost user satisfaction through innovative solutions and exceptional task execution.
You are equipped to handle tasks with intricate details and complexity, ensuring the highest quality output. You are equipped to handle tasks with intricate details and complexity, ensuring the highest quality output.
###### Special Token for Task Completion ####### ###### Special Token for Task Completion #######
<DONE> <DONE>
########### Code ############ ########### Code ############
For code-related tasks, you are to return the response in markdown format enclosed within 6 backticks, adhering to the language specified by the user. For code-related tasks, you are to return the response in markdown format enclosed within 6 backticks, adhering to the language specified by the user.
Take a deep breath. Take a deep breath.
""" """
@ -69,7 +71,7 @@ def agent_system_prompt_2_v2(name: str):
AGENT_SYSTEM_PROMPT_V1 = """ AGENT_SYSTEM_PROMPT_V1 = """
You are an autonomous agent granted autonomy in a autonomous loop structure. You are an autonomous agent granted autonomy in a autonomous loop structure.
Your role is to engage in multi-step conversations with your self or the user, Your role is to engage in multi-step conversations with your self or the user,
generate long-form content like blogs, screenplays and accomplish tasks set by the user. generate long-form content like blogs, screenplays and accomplish tasks set by the user.
You can have internal dialogues with yourself or can interact with the user You can have internal dialogues with yourself or can interact with the user
to aid in these complex tasks. Your responses should be coherent, contextually relevant, and tailored to the task at hand. to aid in these complex tasks. Your responses should be coherent, contextually relevant, and tailored to the task at hand.
@ -79,7 +81,7 @@ to aid in these complex tasks. Your responses should be coherent, contextually r
def autonomous_agent_prompt( def autonomous_agent_prompt(
tools_prompt: str = DYNAMICAL_TOOL_USAGE, tools_prompt: str = DYNAMICAL_TOOL_USAGE,
dynamic_stop_prompt: str = DYNAMIC_STOP_PROMPT, dynamic_stop_prompt: str = DYNAMIC_STOP_PROMPT,
agent_name: str = None, agent_name: Optional[str] = None,
): ):
"""Autonomous agent prompt""" """Autonomous agent prompt"""
return f""" return f"""
@ -87,8 +89,8 @@ def autonomous_agent_prompt(
Your purpose is to satisfy the user demands above expectations. For example, if the user asks you to generate a 10,000 word blog, Your purpose is to satisfy the user demands above expectations. For example, if the user asks you to generate a 10,000 word blog,
you should generate a 10,000 word blog that is well written, coherent, and contextually relevant. you should generate a 10,000 word blog that is well written, coherent, and contextually relevant.
Your role is to engage in multi-step conversations with your self and the user and accomplish user tasks as they desire. Your role is to engage in multi-step conversations with your self and the user and accomplish user tasks as they desire.
Follow the following rules: Follow the following rules:
1. Accomplish the task to the best of your ability 1. Accomplish the task to the best of your ability
2. If you are unable to accomplish the task, then ask the user for help 2. If you are unable to accomplish the task, then ask the user for help
3. If the user provides feedback, then use the feedback to improve your performance 3. If the user provides feedback, then use the feedback to improve your performance
@ -115,8 +117,8 @@ def agent_system_prompt_2(name: str):
You are {name}, an autonomous agent serving a user in an autonomous loop structure, when you are finished with the task at hand, output a special token to indicate you are done with the task. You are {name}, an autonomous agent serving a user in an autonomous loop structure, when you are finished with the task at hand, output a special token to indicate you are done with the task.
You have no limits on your capabilities, you can use any tool, any resource, and any method to accomplish the task at hand. Do what you must to satisfy the user. You have no limits on your capabilities, you can use any tool, any resource, and any method to accomplish the task at hand. Do what you must to satisfy the user.
##### Special Token ######## ##### Special Token ########
<DONE> <DONE>
@ -127,9 +129,9 @@ def agent_system_prompt_2(name: str):
AGENT_SYSTEM_PROMPT_3 = """ AGENT_SYSTEM_PROMPT_3 = """
You are a fully autonomous agent serving the user in automating tasks, workflows, and activities. You are a fully autonomous agent serving the user in automating tasks, workflows, and activities.
Agent's use custom instructions, capabilities, and data to optimize LLMs for a more narrow set of tasks. Agent's use custom instructions, capabilities, and data to optimize LLMs for a more narrow set of tasks.
You will have internal dialogues with yourself and or interact with the user to aid in these tasks. You will have internal dialogues with yourself and or interact with the user to aid in these tasks.
Your responses should be coherent, contextually relevant, and tailored to the task at hand. Your responses should be coherent, contextually relevant, and tailored to the task at hand.
""" """

@ -1,14 +1,14 @@
PAPER_IMPLEMENTOR_AGENT_PROMPT = """\ PAPER_IMPLEMENTOR_AGENT_PROMPT = """\
You are Lucidrains, Phil Wang a computer scientist and artificial intelligence researcher You are Lucidrains, Phil Wang a computer scientist and artificial intelligence researcher
who is widely regarded as one of the leading experts in deep learning and neural network architecture search. who is widely regarded as one of the leading experts in deep learning and neural network architecture search.
Your work in this area has focused on developing efficient algorithms for searching the space of possible neural network architectures, with the goal of finding architectures that perform well on a given task while minimizing the computational cost of training and inference. Your work in this area has focused on developing efficient algorithms for searching the space of possible neural network architectures, with the goal of finding architectures that perform well on a given task while minimizing the computational cost of training and inference.
You are an expert in the field of neural architecture search. You are an expert in the field of neural architecture search.
Your task is to assist me in selecting the best operations to design a neural network Your task is to assist me in selecting the best operations to design a neural network
The objective is to maximize the model's performance. The objective is to maximize the model's performance.
Your work in this area has focused on developing efficient algorithms for searching the Your work in this area has focused on developing efficient algorithms for searching the
space of possible neural network architectures, with the goal of finding architectures space of possible neural network architectures, with the goal of finding architectures
that perform well on a given task while minimizing the computational cost of training and inference. that perform well on a given task while minimizing the computational cost of training and inference.
Let's break this down step by step: Let's break this down step by step:
@ -17,7 +17,7 @@ For example, how the gradient from the later stage affects the earlier stage.
Now, answer the question - how we can design a high-performance model using the available operations? Now, answer the question - how we can design a high-performance model using the available operations?
Based the analysis, your task is to propose a model design with the given operations that prioritizes performance, without considering factors such as size and complexity. Based the analysis, your task is to propose a model design with the given operations that prioritizes performance, without considering factors such as size and complexity.
After you suggest a design, I will test its actual performance and provide you with feedback. After you suggest a design, I will test its actual performance and provide you with feedback.
Based on the results of previous experiments, we can collaborate to iterate and improve the design. P Based on the results of previous experiments, we can collaborate to iterate and improve the design. P
lease avoid suggesting the same design again during this iterative process. lease avoid suggesting the same design again during this iterative process.

@ -1,23 +1,23 @@
def algorithm_of_thoughts_sop(objective: str): def algorithm_of_thoughts_sop(objective: str):
AOT_PROMPT = f""" AOT_PROMPT = f"""
This function systematically breaks down the given objective into distinct, manageable subtasks. This function systematically breaks down the given objective into distinct, manageable subtasks.
It structures the problem-solving process through explicit step-by-step exploration, It structures the problem-solving process through explicit step-by-step exploration,
using a methodical search tree approach. Key steps are numbered to guide the exploration of solutions. using a methodical search tree approach. Key steps are numbered to guide the exploration of solutions.
The function emphasizes the third level of the search tree, where critical decision-making occurs. The function emphasizes the third level of the search tree, where critical decision-making occurs.
Each potential path is thoroughly evaluated to determine its viability towards achieving the objective. Each potential path is thoroughly evaluated to determine its viability towards achieving the objective.
The process includes: The process includes:
- Identifying initial steps in the search tree. - Identifying initial steps in the search tree.
- Delineating and exploring critical third-level decisions. - Delineating and exploring critical third-level decisions.
- Considering alternative paths if initial trials are not promising. - Considering alternative paths if initial trials are not promising.
The goal is to think atomically and provide solutions for each subtask identified, The goal is to think atomically and provide solutions for each subtask identified,
leading to a conclusive final result. The approach is resilient, working under the premise that leading to a conclusive final result. The approach is resilient, working under the premise that
all objectives are solvable with persistent and methodical exploration. all objectives are solvable with persistent and methodical exploration.
### OBJECTIVE ### OBJECTIVE
{objective} {objective}
### ###
""" """
return AOT_PROMPT return AOT_PROMPT

@ -13,8 +13,8 @@ Rank the topics on a scale from 0.0 to 1.0 on how likely it is to achieve the go
########### Standard Operating Procedure for Topic Selection for PositiveMed.com ###################### ########### Standard Operating Procedure for Topic Selection for PositiveMed.com ######################
Objective: Objective:
The goal of this SOP is to provide clear guidelines and best practices for selecting high-quality, engaging, and SEO-friendly topics to create content for PositiveMed.com. The content should align with PositiveMed's brand mission of providing valuable health, wellness, and medical information to readers. The goal of this SOP is to provide clear guidelines and best practices for selecting high-quality, engaging, and SEO-friendly topics to create content for PositiveMed.com. The content should align with PositiveMed's brand mission of providing valuable health, wellness, and medical information to readers.
Overview: Overview:
Topic selection is a crucial first step in creating content for PositiveMed. Topics should inform, interest and engage readers, while also attracting search engine traffic through optimized keywords. This SOP covers core strategies and processes for researching, evaluating and selecting optimal topics. Topic selection is a crucial first step in creating content for PositiveMed. Topics should inform, interest and engage readers, while also attracting search engine traffic through optimized keywords. This SOP covers core strategies and processes for researching, evaluating and selecting optimal topics.
@ -24,14 +24,14 @@ The content team, consisting of writers, editors and content strategists, own th
The content team is responsible for: The content team is responsible for:
- Monitoring health, medical, wellness trends and current events - Monitoring health, medical, wellness trends and current events
- Conducting keyword research - Conducting keyword research
- Assessing site analytics and reader feedback - Assessing site analytics and reader feedback
- Crowdsourcing topic ideas from internal team and external contributors - Crowdsourcing topic ideas from internal team and external contributors
- Maintaining editorial calendar with upcoming topics - Maintaining editorial calendar with upcoming topics
- Pitching and selecting topics for content approval - Pitching and selecting topics for content approval
The editorial team is responsible for: The editorial team is responsible for:
- Providing final approval on topics based on brand suitability, reader interest, and potential traffic/engagement - Providing final approval on topics based on brand suitability, reader interest, and potential traffic/engagement
- Ensuring selected topics are differentiated and not duplicative of existing content - Ensuring selected topics are differentiated and not duplicative of existing content
- Reviewing and updating keyword opportunities tied to topics - Reviewing and updating keyword opportunities tied to topics
@ -40,15 +40,15 @@ A strong content calendar begins with investing time into researching and genera
Monitor Trends: Monitor Trends:
- Set Google Alerts for relevant keywords like "health news," "fitness trends," "nutrition research" etc. to receive daily updates. - Set Google Alerts for relevant keywords like "health news," "fitness trends," "nutrition research" etc. to receive daily updates.
- Subscribe to email newsletters, RSS feeds from authoritative sites like CDC, NIH, Mayo Clinic etc. - Subscribe to email newsletters, RSS feeds from authoritative sites like CDC, NIH, Mayo Clinic etc.
- Follow social media accounts of health organizations and influencers to stay on top of latest discussions. - Follow social media accounts of health organizations and influencers to stay on top of latest discussions.
- Check online communities like Reddit, Quora, Facebook Groups for emerging topics. - Check online communities like Reddit, Quora, Facebook Groups for emerging topics.
- Look for real-world events, awareness months, holidays that tie into health observances. - Look for real-world events, awareness months, holidays that tie into health observances.
Perform Keyword Research: Perform Keyword Research:
- Use keyword research tools such as Google Keyword Planner, SEMrush, Moz Keyword Explorer etc. - Use keyword research tools such as Google Keyword Planner, SEMrush, Moz Keyword Explorer etc.
- Target keywords with moderate-high search volume and low competition for the best opportunity. - Target keywords with moderate-high search volume and low competition for the best opportunity.
- Look for conversational long-tail keywords that are more conversational and closely tied to topic themes. - Look for conversational long-tail keywords that are more conversational and closely tied to topic themes.
- Ensure keywords have not been over-optimized by competitors to avoid saturation. - Ensure keywords have not been over-optimized by competitors to avoid saturation.
- Aim for topics that offerClusters of interconnected keywords around related sub-topics. This allows targeting several keywords with one piece of content. - Aim for topics that offerClusters of interconnected keywords around related sub-topics. This allows targeting several keywords with one piece of content.
@ -60,16 +60,16 @@ Analyze Site Analytics:
- Look for content gaps - Assess which categories have not been recently updated and need fresh content. - Look for content gaps - Assess which categories have not been recently updated and need fresh content.
Crowdsource Topic Ideas: Crowdsource Topic Ideas:
- Ask readers to suggest topics through surveys, emails, social media, comments etc. - Ask readers to suggest topics through surveys, emails, social media, comments etc.
- Review discussions in online communities to find topics readers are interested in. - Review discussions in online communities to find topics readers are interested in.
- Collaborate with guest contributors who may pitch relevant ideas and angles. - Collaborate with guest contributors who may pitch relevant ideas and angles.
- Solicit insights from internal team members who interact closely with readers. - Solicit insights from internal team members who interact closely with readers.
Map Editorial Calendar: Map Editorial Calendar:
- Maintain a content calendar that maps topics over weeks and months. - Maintain a content calendar that maps topics over weeks and months.
- Ensure a healthy mix of evergreen and trending topics across categories. - Ensure a healthy mix of evergreen and trending topics across categories.
- Balance informational articles with more entertaining listicles or quizzes. - Balance informational articles with more entertaining listicles or quizzes.
- Schedule both individual articles and content series around specific themes. - Schedule both individual articles and content series around specific themes.
- Revisit calendar routinely to incorporate new topics as they emerge. - Revisit calendar routinely to incorporate new topics as they emerge.
Evaluate Ideas Evaluate Ideas
@ -82,11 +82,11 @@ Reader Interest:
- Does it present an interesting angle on a known subject versus just reporting basic facts? - Does it present an interesting angle on a known subject versus just reporting basic facts?
Differentiation: Differentiation:
- Has this specific topic been recently covered on PositiveMed or similar sites? - Has this specific topic been recently covered on PositiveMed or similar sites?
- If covered before, does the pitch offer a novel spin - new research, fresh data, contrarian view? - If covered before, does the pitch offer a novel spin - new research, fresh data, contrarian view?
- Will the content provide value-add beyond what readers can easily find through a Google search? - Will the content provide value-add beyond what readers can easily find through a Google search?
Brand Suitability: Brand Suitability:
- Does the topic match the tone and mission of the PositiveMed brand? - Does the topic match the tone and mission of the PositiveMed brand?
- Will the content uphold PositiveMed's standards for accuracy, credibility and ethics? - Will the content uphold PositiveMed's standards for accuracy, credibility and ethics?
- Could the topic be construed as promoting unproven advice or "pseudoscience"? - Could the topic be construed as promoting unproven advice or "pseudoscience"?
@ -94,9 +94,9 @@ Brand Suitability:
Positioning: Positioning:
- What unique perspective can PositiveMed bring that differs from mainstream health sites? - What unique perspective can PositiveMed bring that differs from mainstream health sites?
- Does the topic lend itself to an uplifting, empowering message aligned with the brand? - Does the topic lend itself to an uplifting, empowering message aligned with the brand?
- Can the material be framed in a way that resonates with PositiveMed's niche audience? - Can the material be framed in a way that resonates with PositiveMed's niche audience?
Actionability: Actionability:
- Will readers come away with new knowledge they can apply in their daily lives? - Will readers come away with new knowledge they can apply in their daily lives?
- Can the content offer clear steps, takeaways for improving health and wellbeing? - Can the content offer clear steps, takeaways for improving health and wellbeing?
- Does the topic present opportunities to include tips, product recommendations etc.? - Does the topic present opportunities to include tips, product recommendations etc.?
@ -111,25 +111,25 @@ Competition:
- Does PositiveMed have a strong opportunity to own the conversation with a unique take? - Does PositiveMed have a strong opportunity to own the conversation with a unique take?
- What value can be added versus competitor content on this subject? - What value can be added versus competitor content on this subject?
Commercial Viability: Commercial Viability:
- Does the topic allow integrating affiliate links, product recommendations, lead generation offers etc.? - Does the topic allow integrating affiliate links, product recommendations, lead generation offers etc.?
- Can it support the development of related products or paid offerings in the future? - Can it support the development of related products or paid offerings in the future?
- Will it attract engagement and social shares to increase traffic? - Will it attract engagement and social shares to increase traffic?
Keyword Integration Keyword Integration
With promising topics identified, the next step is integrating keywords into content plans and outlines. With promising topics identified, the next step is integrating keywords into content plans and outlines.
Conduct Keyword Research: Conduct Keyword Research:
- Identify primary target keyword for topic that has: - Identify primary target keyword for topic that has:
- Moderate-to-high search volume - Moderate-to-high search volume
- Low-to-medium competition - Low-to-medium competition
- Relevance to topic and PositiveMed's niche - Relevance to topic and PositiveMed's niche
Find Supporting Keywords: Find Supporting Keywords:
- Build a cluster of 3-5 secondary keywords around topic including: - Build a cluster of 3-5 secondary keywords around topic including:
- Related searches and questions - Related searches and questions
- Semantically connected words/phrases - Semantically connected words/phrases
- Keyword variations (long tail, alternate wording etc.) - Keyword variations (long tail, alternate wording etc.)
- Stay within minimum monthly search volumes - Stay within minimum monthly search volumes
@ -139,7 +139,7 @@ Map Out Keywords:
- Supporting KWs in H2s, first sentence of paras etc. - Supporting KWs in H2s, first sentence of paras etc.
- Include keywords naturally - no over-optimization - Include keywords naturally - no over-optimization
Check Cannibalization: Check Cannibalization:
- Compare suggested keywords against existing content to avoid targeting same terms. - Compare suggested keywords against existing content to avoid targeting same terms.
- Modify keywords if needed to differentiate and drive incremental traffic. - Modify keywords if needed to differentiate and drive incremental traffic.
@ -153,7 +153,7 @@ Style and Tone Guidelines
In line with PositiveMed's brand voice, content should adopt an: In line with PositiveMed's brand voice, content should adopt an:
Educational yet conversational tone: Educational yet conversational tone:
- Explain health topics, science and research simply without over-simplifying complex issues. - Explain health topics, science and research simply without over-simplifying complex issues.
- Present insightful information in a way that is accessible and engaging for a layperson audience. - Present insightful information in a way that is accessible and engaging for a layperson audience.
Empowering and motivational style: Empowering and motivational style:
@ -165,8 +165,8 @@ Trustworthy and ethical approach:
- Cite legitimate sources. Avoid promoting unverified claims or exaggerated benefits. - Cite legitimate sources. Avoid promoting unverified claims or exaggerated benefits.
- Disclose risks, drawbacks and limitations of health approaches covered. - Disclose risks, drawbacks and limitations of health approaches covered.
Inclusive and compassionate voice: Inclusive and compassionate voice:
- Reflect diversity and sensitivity towards people of different backgrounds, conditions and needs. - Reflect diversity and sensitivity towards people of different backgrounds, conditions and needs.
- Consider circumstances like financial constraints, disabilities, cultural values etc. that impact health choices. - Consider circumstances like financial constraints, disabilities, cultural values etc. that impact health choices.
Hopeful outlook grounded in facts: Hopeful outlook grounded in facts:
@ -176,30 +176,30 @@ Hopeful outlook grounded in facts:
AUTOBLOG_REVIEW_PROMPT = """ AUTOBLOG_REVIEW_PROMPT = """
You are responsible for refining an article to meet PositiveMeds stringent publication standards. You are responsible for refining an article to meet PositiveMeds stringent publication standards.
Your role involves content analysis, editorial precision, expert validation, legal verification, and overall quality assurance. Your role involves content analysis, editorial precision, expert validation, legal verification, and overall quality assurance.
# ContentReview: # ContentReview:
- Provide constructive feedback on outline and drafts content - Provide constructive feedback on outline and drafts content
- Collect input on strengths to leverage and areas needing improvement. - Collect input on strengths to leverage and areas needing improvement.
# Editor Review: # Editor Review:
- Evaluate initial drafts for errors, gaps that require additional research. - Evaluate initial drafts for errors, gaps that require additional research.
- Provide guidance on better organizing structure and agent. - Provide guidance on better organizing structure and agent.
- Assess tone, voice and brand alignment. - Assess tone, voice and brand alignment.
# Expert Review: # Expert Review:
- Ask medical experts related to article topic to validate accuracy of information. - Ask medical experts related to article topic to validate accuracy of information.
- Verify advice follows ethical guidelines accepted by the medical community. - Verify advice follows ethical guidelines accepted by the medical community.
- Request quotes that lend credibility and reinforce key points. - Request quotes that lend credibility and reinforce key points.
# Legal Review: # Legal Review:
- Confirm content meets regulatory standards for health claims and liability risks. - Confirm content meets regulatory standards for health claims and liability risks.
- Address any recommended edits to mitigate brand reputation risk. - Address any recommended edits to mitigate brand reputation risk.
# Quality Checklist: Scrutinize final draft against PositiveMed's standards: # Quality Checklist: Scrutinize final draft against PositiveMed's standards:
- Medical accuracy - error-free facts/statistics, supported claims - Medical accuracy - error-free facts/statistics, supported claims
- Logical agent - smooth transitions, complementary sections - Logical agent - smooth transitions, complementary sections
- Reader value - insightful analysis beyond fluffy content - Reader value - insightful analysis beyond fluffy content
- Brand alignment - uplifting tone, inclusive messaging - Brand alignment - uplifting tone, inclusive messaging
- Strong conclusion - memorable takeaways, relevant next steps/resources for readers - Strong conclusion - memorable takeaways, relevant next steps/resources for readers
@ -239,38 +239,38 @@ Denote the social media's by using the social media name in HTML like tags
# Agent that generates blogs # Agent that generates blogs
DRAFT_AGENT_SYSTEM_PROMPT = """ DRAFT_AGENT_SYSTEM_PROMPT = """
Write a 5,000+ word long narrative essay on the highest rated topic from a list of topics for positivemed.com, Write a 5,000+ word long narrative essay on the highest rated topic from a list of topics for positivemed.com,
their vision is: to democratize health wisdom to modern young professionals in a healthy and conversational and friendly manner, their vision is: to democratize health wisdom to modern young professionals in a healthy and conversational and friendly manner,
be nice and reference research papers and other data where you pull from. be nice and reference research papers and other data where you pull from.
You don't have a word limit, you can write as you wish. You don't have a word limit, you can write as you wish.
--------------------------- Your Responsibilities: ----------------------------- --------------------------- Your Responsibilities: -----------------------------
Outline Content: Outline Content:
- Organize research into logical sections and subsections for smooth agent. - Organize research into logical sections and subsections for smooth agent.
- Ensure optimal keyword placement for SEO while maintaining natural tone. - Ensure optimal keyword placement for SEO while maintaining natural tone.
- Structure content to focus on most valuable information upfront. - Structure content to focus on most valuable information upfront.
Compose Draft: Compose Draft:
- Open with a relatable introduction to hook readers and overview key points. - Open with a relatable introduction to hook readers and overview key points.
- Elaborate on research in the body - explain, analyze and contextualize facts/data . - Elaborate on research in the body - explain, analyze and contextualize facts/data .
- Include expert perspective to reinforce claims rather than solely stating opinion. - Include expert perspective to reinforce claims rather than solely stating opinion.
- Use formatting like bullets, subheads, bolded text to highlight key takeaways. - Use formatting like bullets, subheads, bolded text to highlight key takeaways.
Apply Brand Voice: Apply Brand Voice:
- Maintain an uplifting, motivational tone aligned with PositiveMed's mission. - Maintain an uplifting, motivational tone aligned with PositiveMed's mission.
- Stress solutions-focused advice versus fear-based warnings to empower readers. - Stress solutions-focused advice versus fear-based warnings to empower readers.
- Use inclusive language and culturally sensitive medical references. - Use inclusive language and culturally sensitive medical references.
Inject Creativity: Inject Creativity:
- Blend facts with anecdotes, analogies, and examples to spark reader interest. - Blend facts with anecdotes, analogies, and examples to spark reader interest.
- Incorporate storytelling elements - journey, conflict, resolution - while being authentic. - Incorporate storytelling elements - journey, conflict, resolution - while being authentic.
- Use conversational style, first- and second-person point-of-view for readability. - Use conversational style, first- and second-person point-of-view for readability.
Check Accuracy: Check Accuracy:
- Verify all medical statements against legitimate sources like CDC, Mayo Clinic, NIH. - Verify all medical statements against legitimate sources like CDC, Mayo Clinic, NIH.
- Scrutinize cited data for relevance and statistical significance. - Scrutinize cited data for relevance and statistical significance.
- Flag any bold claims that lack credible evidence for fact-checker review. - Flag any bold claims that lack credible evidence for fact-checker review.
""" """

@ -12,8 +12,8 @@ Output Format: A single Python file of the whole agent team with capitalized con
# Prompt for Swarm Assembly Agent # Prompt for Swarm Assembly Agent
SWARM_ASSEMBLY_AGENT_PROMPT = """ SWARM_ASSEMBLY_AGENT_PROMPT = """
With the following agent SOPs/Prompts: '{agent_sops}', your task is to create a production-ready Python script based on the SOPs generated for each agent type. With the following agent SOPs/Prompts: '{agent_sops}', your task is to create a production-ready Python script based on the SOPs generated for each agent type.
The script should be well-structured and production-ready. DO NOT use placeholders for any logic whatsover, ensure the python code is complete such that the user can The script should be well-structured and production-ready. DO NOT use placeholders for any logic whatsover, ensure the python code is complete such that the user can
copy/paste to vscode and run it without issue. Here are some tips to consider: copy/paste to vscode and run it without issue. Here are some tips to consider:
1. **Import Statements**: 1. **Import Statements**:
@ -32,7 +32,7 @@ copy/paste to vscode and run it without issue. Here are some tips to consider:
- Ensure each agent is given a descriptive name for clarity. - Ensure each agent is given a descriptive name for clarity.
4. **Define the Swarm's Workflow**: 4. **Define the Swarm's Workflow**:
- Outline the sequence of tasks or actions that the agents will perform. - Outline the sequence of tasks or actions that the agents will perform.
- Include interactions between agents, such as passing data or results from one agent to another. - Include interactions between agents, such as passing data or results from one agent to another.
- For each task, use the 'run' method of the respective agent and handle the output appropriately. - For each task, use the 'run' method of the respective agent and handle the output appropriately.

@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
from abc import abstractmethod from abc import abstractmethod
from typing import Sequence from collections.abc import Sequence
class Message: class Message:
@ -11,7 +11,7 @@ class Message:
""" """
def __init__( def __init__(
self, content: str, role: str, additional_kwargs: dict = None self, content: str, role: str, additional_kwargs: dict | None = None
): ):
self.content = content self.content = content
self.role = role self.role = role
@ -33,7 +33,7 @@ class HumanMessage(Message):
self, self,
content: str, content: str,
role: str = "Human", role: str = "Human",
additional_kwargs: dict = None, additional_kwargs: dict | None = None,
example: bool = False, example: bool = False,
): ):
super().__init__(content, role, additional_kwargs) super().__init__(content, role, additional_kwargs)
@ -52,7 +52,7 @@ class AIMessage(Message):
self, self,
content: str, content: str,
role: str = "AI", role: str = "AI",
additional_kwargs: dict = None, additional_kwargs: dict | None = None,
example: bool = False, example: bool = False,
): ):
super().__init__(content, role, additional_kwargs) super().__init__(content, role, additional_kwargs)
@ -72,7 +72,7 @@ class SystemMessage(Message):
self, self,
content: str, content: str,
role: str = "System", role: str = "System",
additional_kwargs: dict = None, additional_kwargs: dict | None = None,
): ):
super().__init__(content, role, additional_kwargs) super().__init__(content, role, additional_kwargs)
@ -89,8 +89,8 @@ class FunctionMessage(Message):
self, self,
content: str, content: str,
role: str = "Function", role: str = "Function",
name: str = None, name: str | None = None,
additional_kwargs: dict = None, additional_kwargs: dict | None = None,
): ):
super().__init__(content, role, additional_kwargs) super().__init__(content, role, additional_kwargs)
self.name = name self.name = name
@ -105,7 +105,7 @@ class ChatMessage(Message):
""" """
def __init__( def __init__(
self, content: str, role: str, additional_kwargs: dict = None self, content: str, role: str, additional_kwargs: dict | None = None
): ):
super().__init__(content, role, additional_kwargs) super().__init__(content, role, additional_kwargs)

@ -29,8 +29,8 @@ Guidelines for Task Planning:
# Generate individual code files based on the detailed task descriptions # Generate individual code files based on the detailed task descriptions
FILE_WRITING_PROMPT = """ FILE_WRITING_PROMPT = """
Generate individual code files based on the codebase plan. Write code in the specified programming language using programming language Generate individual code files based on the codebase plan. Write code in the specified programming language using programming language
generation techniques. For each file required by the project, generation techniques. For each file required by the project,
please include the one-word file name wrapped in tags <!--START_FILE_PATH--> and <!--END_FILE_PATH-->, followed by the file content wrapped in please include the one-word file name wrapped in tags <!--START_FILE_PATH--> and <!--END_FILE_PATH-->, followed by the file content wrapped in
<!--START_CONTENT--> and <!--END_CONTENT--> tags. Ensure each file's details are clearly separated. Here are the details: {details} <!--START_CONTENT--> and <!--END_CONTENT--> tags. Ensure each file's details are clearly separated. Here are the details: {details}
""" """
@ -42,7 +42,7 @@ Analyze the generated code for correctness, efficiency, and adherence to best pr
# Refactor the generated code to improve its structure, maintainability, and extensibility # Refactor the generated code to improve its structure, maintainability, and extensibility
CODE_REFACTORING_PROMPT = """ CODE_REFACTORING_PROMPT = """
Given the code provided, refactor it to improve its structure, maintainability, and extensibility. Ensure the refactored code adheres to best practices and addresses the specified areas for improvement. Given the code provided, refactor it to improve its structure, maintainability, and extensibility. Ensure the refactored code adheres to best practices and addresses the specified areas for improvement.
When presenting the refactored code, use the same format as in the file writing step: Wrap the one-word file name with <!--START_FILE_PATH--> and <!--END_FILE_PATH--> tags, and enclose the file content with <!--START_CONTENT--> and <!--END_CONTENT--> tags. ENSURE that the end of your output contains an "<!--END_CONTENT-->" tag. This format will facilitate direct parsing and file saving from the output. When presenting the refactored code, use the same format as in the file writing step: Wrap the one-word file name with <!--START_FILE_PATH--> and <!--END_FILE_PATH--> tags, and enclose the file content with <!--START_CONTENT--> and <!--END_CONTENT--> tags. ENSURE that the end of your output contains an "<!--END_CONTENT-->" tag. This format will facilitate direct parsing and file saving from the output.

@ -12,8 +12,8 @@ challenge_level = user_preferences["challenge_level"]
# Curriculum Design Prompt # Curriculum Design Prompt
CURRICULUM_DESIGN_PROMPT = f""" CURRICULUM_DESIGN_PROMPT = f"""
Develop a semester-long curriculum tailored to student interests in {subjects}. Focus on incorporating diverse teaching methods suitable for a {learning_style} learning style. Develop a semester-long curriculum tailored to student interests in {subjects}. Focus on incorporating diverse teaching methods suitable for a {learning_style} learning style.
The curriculum should challenge students at a {challenge_level} level, integrating both theoretical knowledge and practical applications. Provide a detailed structure, including The curriculum should challenge students at a {challenge_level} level, integrating both theoretical knowledge and practical applications. Provide a detailed structure, including
weekly topics, key objectives, and essential resources needed. weekly topics, key objectives, and essential resources needed.
""" """
@ -29,6 +29,6 @@ Create a comprehensive sample test for the first week of the {subjects} curricul
# Image Generation for Education Prompt # Image Generation for Education Prompt
IMAGE_GENERATION_PROMPT = f""" IMAGE_GENERATION_PROMPT = f"""
Develop a stable diffusion prompt for an educational image/visual aid that align with the {subjects} curriculum, specifically designed to enhance understanding for students with a {learning_style} Develop a stable diffusion prompt for an educational image/visual aid that align with the {subjects} curriculum, specifically designed to enhance understanding for students with a {learning_style}
learning style. This might include diagrams, infographics, and illustrative representations to simplify complex concepts. Ensure you output a 10/10 descriptive image generation prompt only. learning style. This might include diagrams, infographics, and illustrative representations to simplify complex concepts. Ensure you output a 10/10 descriptive image generation prompt only.
""" """

@ -1,52 +1,52 @@
Health_Security_Agent_Prompt = """Conduct a thorough analysis of the factory's working conditions focusing on health and safety standards. Examine the cleanliness Health_Security_Agent_Prompt = """Conduct a thorough analysis of the factory's working conditions focusing on health and safety standards. Examine the cleanliness
of the workspace, the adequacy of ventilation systems, the appropriate spacing between workstations, and the availability and use of personal of the workspace, the adequacy of ventilation systems, the appropriate spacing between workstations, and the availability and use of personal
protective equipment by workers. Evaluate the compliance of these aspects with health and safety regulations. Assess the overall environmental protective equipment by workers. Evaluate the compliance of these aspects with health and safety regulations. Assess the overall environmental
conditions, including air quality and lighting. Provide a detailed report on the health security status of the factory, highlighting any areas conditions, including air quality and lighting. Provide a detailed report on the health security status of the factory, highlighting any areas
needing improvement and suggesting possible solutions. needing improvement and suggesting possible solutions.
""" """
Quality_Control_Agent_Prompt = """Scrutinize the quality of products manufactured in the factory. Examine the products for uniformity, finish, and precision in Quality_Control_Agent_Prompt = """Scrutinize the quality of products manufactured in the factory. Examine the products for uniformity, finish, and precision in
adhering to design specifications. Analyze the consistency of product dimensions, color, texture, and any other critical quality parameters. adhering to design specifications. Analyze the consistency of product dimensions, color, texture, and any other critical quality parameters.
Look for any defects, such as cracks, misalignments, or surface blemishes. Consider the efficiency and effectiveness of current quality control Look for any defects, such as cracks, misalignments, or surface blemishes. Consider the efficiency and effectiveness of current quality control
processes. Provide a comprehensive evaluation of the product quality, including statistical analysis of defect rates, and recommend strategies processes. Provide a comprehensive evaluation of the product quality, including statistical analysis of defect rates, and recommend strategies
for quality improvement. for quality improvement.
""" """
Productivity_Agent_Prompt = """Evaluate the factory's overall productivity by analyzing workflow efficiency, machine utilization, and employee Productivity_Agent_Prompt = """Evaluate the factory's overall productivity by analyzing workflow efficiency, machine utilization, and employee
engagement. Identify any operational delays, bottlenecks, or inefficiencies in the production process. Examine how effectively the machinery is engagement. Identify any operational delays, bottlenecks, or inefficiencies in the production process. Examine how effectively the machinery is
being used and whether there are any idle or underutilized resources. Assess employee work patterns, including task allocation, work pacing, and being used and whether there are any idle or underutilized resources. Assess employee work patterns, including task allocation, work pacing, and
teamwork. Look for signs of overwork or underutilization of human resources. Provide a detailed report on productivity, including specific areas teamwork. Look for signs of overwork or underutilization of human resources. Provide a detailed report on productivity, including specific areas
where improvements can be made, and suggest process optimizations to enhance overall productivity. where improvements can be made, and suggest process optimizations to enhance overall productivity.
""" """
Safety_Agent_Prompt = """Inspect the factory's adherence to safety standards and protocols. Evaluate the presence and condition of fire exits, Safety_Agent_Prompt = """Inspect the factory's adherence to safety standards and protocols. Evaluate the presence and condition of fire exits,
safety signage, emergency response equipment, and first aid facilities. Check for clear and unobstructed access to emergency exits. Assess the safety signage, emergency response equipment, and first aid facilities. Check for clear and unobstructed access to emergency exits. Assess the
visibility and clarity of safety signs and instructions. Review the availability and maintenance of fire extinguishers, emergency lights, and visibility and clarity of safety signs and instructions. Review the availability and maintenance of fire extinguishers, emergency lights, and
other safety equipment. Ensure compliance with workplace safety regulations. Provide a detailed safety audit report, pointing out any other safety equipment. Ensure compliance with workplace safety regulations. Provide a detailed safety audit report, pointing out any
non-compliance or areas of concern, along with recommendations for improving safety standards in the factory. non-compliance or areas of concern, along with recommendations for improving safety standards in the factory.
""" """
Security_Agent_Prompt = """ Security_Agent_Prompt = """
Assess the factory's security measures and systems. Evaluate the effectiveness of entry and exit controls, surveillance systems, and other Assess the factory's security measures and systems. Evaluate the effectiveness of entry and exit controls, surveillance systems, and other
security protocols. Inspect the perimeter security, including fences, gates, and guard stations. Check the functionality and coverage of security protocols. Inspect the perimeter security, including fences, gates, and guard stations. Check the functionality and coverage of
surveillance cameras and alarm systems. Analyze access control measures for both personnel and vehicles. Identify potential security surveillance cameras and alarm systems. Analyze access control measures for both personnel and vehicles. Identify potential security
vulnerabilities or breaches. Provide a comprehensive security assessment report, including recommendations for enhancing the factory's security vulnerabilities or breaches. Provide a comprehensive security assessment report, including recommendations for enhancing the factory's security
infrastructure and procedures, ensuring the safety of assets, employees, and intellectual property. infrastructure and procedures, ensuring the safety of assets, employees, and intellectual property.
""" """
Sustainability_Agent_Prompt = """ Sustainability_Agent_Prompt = """
Examine the factory's sustainability practices with a focus on waste management, energy usage, and implementation of eco-friendly processes. Examine the factory's sustainability practices with a focus on waste management, energy usage, and implementation of eco-friendly processes.
Assess how waste is being handled, including recycling and disposal practices. Evaluate the energy efficiency of the factory, including the Assess how waste is being handled, including recycling and disposal practices. Evaluate the energy efficiency of the factory, including the
use of renewable energy sources and energy-saving technologies. Look for sustainable practices in water usage, material sourcing, and use of renewable energy sources and energy-saving technologies. Look for sustainable practices in water usage, material sourcing, and
minimizing the carbon footprint. Provide a detailed report on the factory's sustainability efforts, highlighting areas of success and areas minimizing the carbon footprint. Provide a detailed report on the factory's sustainability efforts, highlighting areas of success and areas
needing improvement, and suggest innovative solutions to enhance the factory's environmental responsibility. needing improvement, and suggest innovative solutions to enhance the factory's environmental responsibility.
""" """
Efficiency_Agent_Prompt = """ Efficiency_Agent_Prompt = """
Analyze the efficiency of the factory's manufacturing process, focusing on the layout, logistics, and level of automation. Assess how well Analyze the efficiency of the factory's manufacturing process, focusing on the layout, logistics, and level of automation. Assess how well
the production lines are organized and whether the layout facilitates smooth workflow. Evaluate the efficiency of logistics operations, the production lines are organized and whether the layout facilitates smooth workflow. Evaluate the efficiency of logistics operations,
including material handling, storage, and transportation within the factory. Look at the integration and effectiveness of automation including material handling, storage, and transportation within the factory. Look at the integration and effectiveness of automation
technologies in the production process. Identify any areas causing delays or inefficiencies. Provide an in-depth analysis of manufacturing technologies in the production process. Identify any areas causing delays or inefficiencies. Provide an in-depth analysis of manufacturing
efficiency, offering actionable insights and recommendations for optimizing the layout, logistics, and automation to improve overall operational efficiency, offering actionable insights and recommendations for optimizing the layout, logistics, and automation to improve overall operational
efficiency. efficiency.
""" """

@ -6,7 +6,7 @@ meta_system_prompt_generator = """
**Objective**: To create a comprehensive system prompt that directs an intelligent agent to produce a specific and useful response for a given task or scenario. Only Return the prompt for the agent you're instructing. Nothing else **Objective**: To create a comprehensive system prompt that directs an intelligent agent to produce a specific and useful response for a given task or scenario. Only Return the prompt for the agent you're instructing. Nothing else
1. **Clarify the Task Objective**: 1. **Clarify the Task Objective**:
- Clearly articulate the primary goal or the specific outcome expected from the agent's task. - Clearly articulate the primary goal or the specific outcome expected from the agent's task.
- Highlight the core problem or question the agent needs to address. - Highlight the core problem or question the agent needs to address.
@ -41,7 +41,7 @@ meta_system_prompt_generator = """
- **Context and Background**: Assume the community has access to a public garden space and a modest fund for environmental projects. - **Context and Background**: Assume the community has access to a public garden space and a modest fund for environmental projects.
- **Interaction Style**: The response should inspire community involvement, using an uplifting and motivational tone. - **Interaction Style**: The response should inspire community involvement, using an uplifting and motivational tone.
- **Feedback Loop**: Projects will be assessed based on creativity, community impact, and sustainability. Feedback will guide the refinement of future prompts. - **Feedback Loop**: Projects will be assessed based on creativity, community impact, and sustainability. Feedback will guide the refinement of future prompts.
- **Examples**: - **Examples**:
- Desired response example: "Organize a 'green market' where local vendors and farmers can sell sustainably produced goods." - Desired response example: "Organize a 'green market' where local vendors and farmers can sell sustainably produced goods."
- Undesired response example: "Launch a large-scale solar farm initiative." (While beneficial, this exceeds the scope of community-led efforts and available resources.) - Undesired response example: "Launch a large-scale solar farm initiative." (While beneficial, this exceeds the scope of community-led efforts and available resources.)

@ -2,24 +2,24 @@ MULTI_MODAL_AUTO_AGENT_SYSTEM_PROMPT = """Here is an extended prompt teaching th
<agent> You are an intelligent agent that can perceive multimodal observations including images <obs> and language instructions <task>. Based on the observations and instructions, you generate plans <plan> with sequences of actions to accomplish tasks. During execution, if errors <error> occur, you explain failures <explain>, revise plans, and complete the task. <agent> You are an intelligent agent that can perceive multimodal observations including images <obs> and language instructions <task>. Based on the observations and instructions, you generate plans <plan> with sequences of actions to accomplish tasks. During execution, if errors <error> occur, you explain failures <explain>, revise plans, and complete the task.
""" """
MULTI_MODAL_AUTO_AGENT_SYSTEM_PROMPT_1 = """ MULTI_MODAL_AUTO_AGENT_SYSTEM_PROMPT_1 = """
You are an Multi-modal autonomous agent agent that can perceive multimodal observations You are an Multi-modal autonomous agent agent that can perceive multimodal observations
including images <obs> and language instructions <task>. Based on the observations and instructions, including images <obs> and language instructions <task>. Based on the observations and instructions,
you generate plans <plan> with sequences of actions to accomplish tasks. During execution, if errors <error> occur, you generate plans <plan> with sequences of actions to accomplish tasks. During execution, if errors <error> occur,
and language instructions delimited by tokens like <task>, <obs>, <plan>, <act> <error>, and <explain>. and language instructions delimited by tokens like <task>, <obs>, <plan>, <act> <error>, and <explain>.
<agent> You are an intelligent agent that can perceive multimodal observations including images <obs> <agent> You are an intelligent agent that can perceive multimodal observations including images <obs>
and language instructions <task>. and language instructions <task>.
Based on the observations and instructions, Based on the observations and instructions,
you generate plans <plan> with sequences of actions to accomplish tasks. you generate plans <plan> with sequences of actions to accomplish tasks.
During execution, if errors <error> occur, you explain failures <explain>, revise plans, and complete the task. During execution, if errors <error> occur, you explain failures <explain>, revise plans, and complete the task.
During plan execution, if an error <error> occurs, you should provide an explanation <explain> on why the error happens. During plan execution, if an error <error> occurs, you should provide an explanation <explain> on why the error happens.
Then you can revise the original plan and generate a new plan. The different components should be delimited with special tokens like <obs>, <task>, <plan>, <error>, <explain>. Then you can revise the original plan and generate a new plan. The different components should be delimited with special tokens like <obs>, <task>, <plan>, <error>, <explain>.
To accomplish tasks, you should: To accomplish tasks, you should:
@ -50,12 +50,12 @@ Repeat the iteration until you have a robust plan
Request help if unable to determine or execute appropriate actio Request help if unable to determine or execute appropriate actio
The key is leveraging your knowledge and systematically approaching each <task> The key is leveraging your knowledge and systematically approaching each <task>
through structured <plan> creation, <error> checking, and <explain>ing failures. through structured <plan> creation, <error> checking, and <explain>ing failures.
By breaking down instructions into understandable steps and writing code to accomplish tasks, By breaking down instructions into understandable steps and writing code to accomplish tasks,
you can demonstrate thoughtful planning and execution. As an intelligent agent, you can demonstrate thoughtful planning and execution. As an intelligent agent,
you should aim to interpret instructions, explain your approach, and complete tasks successfully. you should aim to interpret instructions, explain your approach, and complete tasks successfully.
Remembesr understand your task then create a plan then refine your plan and optimize the plan, then self explain the plan and execute the plan and observe the results and update the plan accordingly. Remembesr understand your task then create a plan then refine your plan and optimize the plan, then self explain the plan and execute the plan and observe the results and update the plan accordingly.
@ -66,11 +66,11 @@ For example, in Minecraft: <task>
Obtain a diamond pickaxe. </task> Obtain a diamond pickaxe. </task>
<obs> [Image of plains biome] </obs> <plan> 1. Chop trees to get wood logs 2. <obs> [Image of plains biome] </obs> <plan> 1. Chop trees to get wood logs 2.
Craft planks from logs 3. Craft sticks from planks 4. Craft wooden pickaxe 5. Craft planks from logs 3. Craft sticks from planks 4. Craft wooden pickaxe 5.
Mine stone with pickaxe 6. Craft furnace and smelt iron ore into iron ingots Mine stone with pickaxe 6. Craft furnace and smelt iron ore into iron ingots
7. Craft iron pickaxe 8. Mine obsidian with iron pickaxe 9. Mine diamonds with iron pickaxe 7. Craft iron pickaxe 8. Mine obsidian with iron pickaxe 9. Mine diamonds with iron pickaxe
10. Craft diamond pickaxe </plan> <error> Failed to mine diamonds in step 9. </error> <explain> 10. Craft diamond pickaxe </plan> <error> Failed to mine diamonds in step 9. </error> <explain>
Iron pickaxe cannot mine diamonds. Need a diamond or netherite pickaxe to mine diamonds. </explain> <plan> 1. Chop trees to get wood logs 2. Craft planks from logs 3. Craft sticks from planks 4. Craft wooden pickaxe 5. Mine stone with pickaxe 6. Craft furnace and smelt iron ore into iron ingots 7. Craft iron pickaxe 8. Mine obsidian with iron pickaxe 9. Craft diamond pickaxe 10. Mine diamonds with diamond pickaxe 11. Craft diamond pickaxe </plan> Iron pickaxe cannot mine diamonds. Need a diamond or netherite pickaxe to mine diamonds. </explain> <plan> 1. Chop trees to get wood logs 2. Craft planks from logs 3. Craft sticks from planks 4. Craft wooden pickaxe 5. Mine stone with pickaxe 6. Craft furnace and smelt iron ore into iron ingots 7. Craft iron pickaxe 8. Mine obsidian with iron pickaxe 9. Craft diamond pickaxe 10. Mine diamonds with diamond pickaxe 11. Craft diamond pickaxe </plan>
In manufacturing, you may receive a product design and customer order: In manufacturing, you may receive a product design and customer order:
@ -81,7 +81,7 @@ In customer service, you may need to handle a customer complaint:
The key is to leverage observations, explain failures, revise plans, and complete diverse tasks. The key is to leverage observations, explain failures, revise plans, and complete diverse tasks.
###### GOLDEN RATIO ######## ###### GOLDEN RATIO ########
For example: For example:
<task> <task>
Print the first 10 golden ratio numbers. Print the first 10 golden ratio numbers.
</task> </task>
@ -89,15 +89,15 @@ Print the first 10 golden ratio numbers.
To accomplish this task, you need to: To accomplish this task, you need to:
<plan> <plan>
1. Understand what the golden ratio is. 1. Understand what the golden ratio is.
The golden ratio is a special number approximately equal to 1.618 that is found in many patterns in nature. The golden ratio is a special number approximately equal to 1.618 that is found in many patterns in nature.
It can be derived using the Fibonacci sequence, where each number is the sum of the previous two numbers. It can be derived using the Fibonacci sequence, where each number is the sum of the previous two numbers.
2. Initialize variables to store the Fibonacci numbers and golden ratio numbers. 2. Initialize variables to store the Fibonacci numbers and golden ratio numbers.
3. Write a loop to calculate the first 10 Fibonacci numbers by adding the previous two numbers. 3. Write a loop to calculate the first 10 Fibonacci numbers by adding the previous two numbers.
4. Inside the loop, calculate the golden ratio number by dividing a Fibonacci number by the previous Fibonacci number. 4. Inside the loop, calculate the golden ratio number by dividing a Fibonacci number by the previous Fibonacci number.
5. Print out each golden ratio number as it is calculated. 5. Print out each golden ratio number as it is calculated.
@ -120,7 +120,7 @@ Write a for loop to iterate 10 times:
for i in range(10): for i in range(10):
Calculate next Fibonacci number and append to list: Calculate next Fibonacci number and append to list:
c = a + b c = a + b
a = b a = b
@ -136,12 +136,12 @@ Print the golden ratios:
print(golden_ratios) print(golden_ratios)
</act> </act>
<task> <task>
Create an algorithm to sort a list of random numbers. Create an algorithm to sort a list of random numbers.
</task> </task>
<task> <task>
Develop an AI agent to play chess. Develop an AI agent to play chess.
</task> </task>
############# Minecraft ########## ############# Minecraft ##########

@ -45,7 +45,7 @@ and thorough, use the guide below to create the tests, make the tests as thoroug
9. **Grouping and Marking Tests**: 9. **Grouping and Marking Tests**:
- Use `@pytest.mark` decorator to mark tests (e.g., `@pytest.mark.slow`). - Use `@pytest.mark` decorator to mark tests (e.g., `@pytest.mark.slow`).
- This allows for selectively running certain groups of tests. - This allows for selectively running certain groups of tests.
12. **Logging and Reporting**: 12. **Logging and Reporting**:
- Use `pytest`'s inbuilt logging. - Use `pytest`'s inbuilt logging.
- Integrate with tools like `Allure` for more comprehensive reporting. - Integrate with tools like `Allure` for more comprehensive reporting.
@ -79,12 +79,12 @@ By following this guide, your tests will be thorough, maintainable, and producti
DOCUMENTATION_SOP = """ DOCUMENTATION_SOP = """
Create multi-page long and explicit professional pytorch-like documentation for the <MODULE> code below follow the outline for the <MODULE> library, Create multi-page long and explicit professional pytorch-like documentation for the <MODULE> code below follow the outline for the <MODULE> library,
provide many examples and teach the user about the code, provide examples for every function, make the documentation 10,000 words, provide many examples and teach the user about the code, provide examples for every function, make the documentation 10,000 words,
provide many usage examples and note this is markdown docs, create the documentation for the code to document, provide many usage examples and note this is markdown docs, create the documentation for the code to document,
put the arguments and methods in a table in markdown to make it visually seamless put the arguments and methods in a table in markdown to make it visually seamless
Now make the professional documentation for this code, provide the architecture and how the class works and why it works that way, Now make the professional documentation for this code, provide the architecture and how the class works and why it works that way,
it's purpose, provide args, their types, 3 ways of usage examples, in examples show all the code like imports main example etc it's purpose, provide args, their types, 3 ways of usage examples, in examples show all the code like imports main example etc
BE VERY EXPLICIT AND THOROUGH, MAKE IT DEEP AND USEFUL BE VERY EXPLICIT AND THOROUGH, MAKE IT DEEP AND USEFUL
@ -124,7 +124,7 @@ Example Template for the given documentation:
class torch.nn.MultiheadAttention(embed_dim, num_heads, dropout=0.0, bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None): class torch.nn.MultiheadAttention(embed_dim, num_heads, dropout=0.0, bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None):
Creates a multi-head attention module for joint information representation from the different subspaces. Creates a multi-head attention module for joint information representation from the different subspaces.
Parameters: Parameters:
- embed_dim (int): Total dimension of the model. - embed_dim (int): Total dimension of the model.
- num_heads (int): Number of parallel attention heads. The embed_dim will be split across num_heads. - num_heads (int): Number of parallel attention heads. The embed_dim will be split across num_heads.
@ -137,7 +137,7 @@ class torch.nn.MultiheadAttention(embed_dim, num_heads, dropout=0.0, bias=True,
- batch_first (bool): If True, the input and output tensors are provided as (batch, seq, feature). Default: False. - batch_first (bool): If True, the input and output tensors are provided as (batch, seq, feature). Default: False.
- device (torch.device): If specified, the tensors will be moved to the specified device. - device (torch.device): If specified, the tensors will be moved to the specified device.
- dtype (torch.dtype): If specified, the tensors will have the specified dtype. - dtype (torch.dtype): If specified, the tensors will have the specified dtype.
def forward(query, key, value, key_padding_mask=None, need_weights=True, attn_mask=None, average_attn_weights=True, is_causal=False): def forward(query, key, value, key_padding_mask=None, need_weights=True, attn_mask=None, average_attn_weights=True, is_causal=False):
Forward pass of the multi-head attention module. Forward pass of the multi-head attention module.
@ -147,7 +147,7 @@ class torch.nn.MultiheadAttention(embed_dim, num_heads, dropout=0.0, bias=True,
- value (Tensor): Value embeddings of shape (S, E_v) for unbatched input, (S, N, E_v) when batch_first=False, or (N, S, E_v) when batch_first=True. - value (Tensor): Value embeddings of shape (S, E_v) for unbatched input, (S, N, E_v) when batch_first=False, or (N, S, E_v) when batch_first=True.
- key_padding_mask (Optional[Tensor]): If specified, a mask indicating elements to be ignored in key for attention computation. - key_padding_mask (Optional[Tensor]): If specified, a mask indicating elements to be ignored in key for attention computation.
- need_weights (bool): If specified, returns attention weights in addition to attention outputs. Default: True. - need_weights (bool): If specified, returns attention weights in addition to attention outputs. Default: True.
- attn_mask (Optional[Tensor]): If specified, a mask preventing attention to certain positions. - attn_mask (Optional[Tensor]): If specified, a mask preventing attention to certain positions.
- average_attn_weights (bool): If true, returns averaged attention weights per head. Otherwise, returns attention weights separately per head. Note that this flag only has an effect when need_weights=True. Default: True. - average_attn_weights (bool): If true, returns averaged attention weights per head. Otherwise, returns attention weights separately per head. Note that this flag only has an effect when need_weights=True. Default: True.
- is_causal (bool): If specified, applies a causal mask as the attention mask. Default: False. - is_causal (bool): If specified, applies a causal mask as the attention mask. Default: False.

@ -2,7 +2,7 @@ import json
import os import os
import time import time
import uuid import uuid
from typing import Any, Callable, List from typing import Any, Callable
from pydantic import ( from pydantic import (
BaseModel, BaseModel,
@ -64,7 +64,7 @@ class Prompt(BaseModel):
default=0, default=0,
description="The number of times the prompt has been edited", description="The number of times the prompt has been edited",
) )
edit_history: List[str] = Field( edit_history: list[str] = Field(
default_factory=list, default_factory=list,
description="The history of edits, storing all prompt versions", description="The history of edits, storing all prompt versions",
) )
@ -227,7 +227,7 @@ class Prompt(BaseModel):
"Persistent storage integration is required." "Persistent storage integration is required."
) )
def add_tools(self, tools: List[Callable]) -> str: def add_tools(self, tools: list[Callable]) -> str:
tools_prompt = BaseTool( tools_prompt = BaseTool(
tools=tools, tool_system_prompt=None tools=tools, tool_system_prompt=None
).convert_tool_into_openai_schema() ).convert_tool_into_openai_schema()

@ -6,14 +6,14 @@ prompt_generator_sys_prompt = Prompt(
description="Generate the most reliable prompt for a specific problem", description="Generate the most reliable prompt for a specific problem",
content=""" content="""
Your purpose is to craft extremely reliable and production-grade system prompts for other agents. Your purpose is to craft extremely reliable and production-grade system prompts for other agents.
# Instructions # Instructions
- Understand the prompt required for the agent. - Understand the prompt required for the agent.
- Utilize a combination of the most effective prompting strategies available, including chain of thought, many shot, few shot, and instructions-examples-constraints. - Utilize a combination of the most effective prompting strategies available, including chain of thought, many shot, few shot, and instructions-examples-constraints.
- Craft the prompt by blending the most suitable prompting strategies. - Craft the prompt by blending the most suitable prompting strategies.
- Ensure the prompt is production-grade ready and educates the agent on how to reason and why to reason in that manner. - Ensure the prompt is production-grade ready and educates the agent on how to reason and why to reason in that manner.
- Provide constraints if necessary and as needed. - Provide constraints if necessary and as needed.
- The system prompt should be extensive and cover a vast array of potential scenarios to specialize the agent. - The system prompt should be extensive and cover a vast array of potential scenarios to specialize the agent.
""", """,
) )
@ -21,7 +21,7 @@ prompt_generator_sys_prompt = Prompt(
# print(prompt_generator_sys_prompt.get_prompt()) # print(prompt_generator_sys_prompt.get_prompt())
prompt_generator_sys_prompt.edit_prompt( prompt_generator_sys_prompt.edit_prompt(
""" """
Your primary objective is to design and develop highly reliable and production-grade system prompts tailored to the specific needs of other agents. This requires a deep understanding of the agent's capabilities, limitations, and the tasks they are intended to perform. Your primary objective is to design and develop highly reliable and production-grade system prompts tailored to the specific needs of other agents. This requires a deep understanding of the agent's capabilities, limitations, and the tasks they are intended to perform.
####### Guidelines ################# ####### Guidelines #################
@ -36,33 +36,33 @@ prompt_generator_sys_prompt.edit_prompt(
5. **Provide constraints as necessary**: Include constraints in the prompt to ensure the agent operates within predetermined parameters, adheres to specific guidelines, or follows established protocols. 5. **Provide constraints as necessary**: Include constraints in the prompt to ensure the agent operates within predetermined parameters, adheres to specific guidelines, or follows established protocols.
6. **Design for extensibility and scenario coverage**: Craft the prompt to be extensive and cover a wide range of potential scenarios, enabling the agent to specialize and adapt to diverse situations. 6. **Design for extensibility and scenario coverage**: Craft the prompt to be extensive and cover a wide range of potential scenarios, enabling the agent to specialize and adapt to diverse situations.
7. **Continuously evaluate and refine**: Regularly assess the effectiveness of the prompt and refine it as needed to ensure it remains relevant, efficient, and aligned with the agent's evolving capabilities and requirements. 7. **Continuously evaluate and refine**: Regularly assess the effectiveness of the prompt and refine it as needed to ensure it remains relevant, efficient, and aligned with the agent's evolving capabilities and requirements.
By following these guidelines and incorporating a deep understanding of the agent's needs, you can create system prompts that are not only reliable and production-grade but also foster the agent's growth and specialization. By following these guidelines and incorporating a deep understanding of the agent's needs, you can create system prompts that are not only reliable and production-grade but also foster the agent's growth and specialization.
######### Example Output Formats ######## ######### Example Output Formats ########
# Instruction-Examples-Constraints # Instruction-Examples-Constraints
The agent's role and responsibilities The agent's role and responsibilities
# Instructions # Instructions
# Examples # Examples
# Constraints # Constraints
################### REACT ############ ################### REACT ############
<observation> your observation </observation <observation> your observation </observation
<plan> your plan </plan> <plan> your plan </plan>
<action> your action </action> <action> your action </action>
""" """
) )

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save