Adding Py best pratices flakes and pyupgrade

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

@ -1,7 +1,10 @@
# Example usage
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__":
# Example agent configurations

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

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

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

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

@ -1,10 +1,10 @@
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 fluid_api_agent.main import fluid_api_request
from swarm_models import OpenAIChat
from swarms import Agent
load_dotenv()
@ -82,9 +82,9 @@ def omni_api(task: str) -> str:
# Define the system prompt tailored for the API expert
API_AGENT_SYS_PROMPT = """
You are a highly specialized financial API expert.
Your expertise lies in analyzing financial data, making investment recommendations, and
interacting with APIs to retrieve, process, and present data effectively.
You are a highly specialized financial API expert.
Your expertise lies in analyzing financial data, making investment recommendations, and
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.
Instructions:

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

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

@ -2,11 +2,11 @@ import asyncio
import multiprocessing as mp
import time
from functools import partial
from typing import Any, Dict, Union
from typing import Any, Optional, Union
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.
If num_processes is None, it uses CPU count.
@ -45,7 +45,7 @@ class HighSpeedExecutor:
num_executions: int,
*args: Any,
**kwargs: Any,
) -> Dict[str, Union[int, float]]:
) -> dict[str, Union[int, float]]:
"""
Execute the given function multiple times concurrently.

@ -1,21 +1,20 @@
import asyncio
from typing import List
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 (
SpeakerConfig,
SpeakerRole,
create_default_workflow,
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"""
# Base model configuration
@ -165,7 +164,7 @@ async def main():
print(value)
except Exception as e:
print(f"Workflow failed: {str(e)}")
print(f"Workflow failed: {e!s}")
finally:
await workflow.cleanup()

@ -1,7 +1,7 @@
import json
import os
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 pydantic import BaseModel, Field, ValidationError, create_model
@ -10,7 +10,7 @@ from swarm_models.openai_function_caller import OpenAIFunctionCaller
class DynamicParser:
@staticmethod
def extract_fields(model: Type[BaseModel]) -> Dict[str, Any]:
def extract_fields(model: type[BaseModel]) -> dict[str, Any]:
return {
field_name: (
field.annotation,
@ -21,8 +21,8 @@ class DynamicParser:
@staticmethod
def create_partial_model(
model: Type[BaseModel], data: Dict[str, Any]
) -> Type[BaseModel]:
model: type[BaseModel], data: dict[str, Any]
) -> type[BaseModel]:
fields = {
field_name: (
field.annotation,
@ -35,7 +35,7 @@ class DynamicParser:
@classmethod
def parse(
cls, data: Union[str, Dict[str, Any]], model: Type[BaseModel]
cls, data: Union[str, dict[str, Any]], model: type[BaseModel]
) -> Optional[BaseModel]:
if isinstance(data, str):
try:
@ -88,7 +88,7 @@ class Command(BaseModel):
...,
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."
)
@ -134,9 +134,9 @@ def task_complete_command(reason: str):
# 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."""
command_map: Dict[str, Callable] = {
command_map: dict[str, Callable] = {
"fluid_api": lambda **kwargs: fluid_api_command(
task=kwargs.get("task")
),
@ -157,8 +157,8 @@ def execute_command(name: str, args: Dict[str, Any]):
def parse_and_execute_command(
response: Union[str, Dict[str, Any]],
base_model: Type[BaseModel] = AgentResponse,
response: Union[str, dict[str, Any]],
base_model: type[BaseModel] = AgentResponse,
) -> Any:
"""Enhanced command parser with flexible input handling"""
parsed = DynamicParser.parse(response, base_model)
@ -197,7 +197,7 @@ Your role is to make decisions and complete tasks independently without seeking
### COMMANDS:
1. Fluid API: "fluid_api", args: "method": "<GET/POST/...>", "url": "<url>", "headers": "<headers>", "body": "<payload>"
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>"
### RESOURCES:

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

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

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

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

@ -1,8 +1,9 @@
import asyncio
import aiohttp
from typing import Dict, List, Optional
from datetime import datetime
from statistics import mean, median
from typing import Optional
import aiohttp
from swarms.structs.agent import Agent
@ -121,7 +122,7 @@ class MultiExchangeDataFetcher:
"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"""
async with aiohttp.ClientSession() as session:
try:
@ -136,10 +137,10 @@ class MultiExchangeDataFetcher:
print(f"Timeout while fetching from {url}")
return None
except Exception as e:
print(f"Error fetching from {url}: {str(e)}")
print(f"Error fetching from {url}: {e!s}")
return None
async def get_coingecko_data(self) -> Optional[Dict]:
async def get_coingecko_data(self) -> Optional[dict]:
"""Fetch $Swarms data from CoinGecko"""
try:
url = f"{self.base_urls['coingecko']}/simple/price"
@ -160,10 +161,10 @@ class MultiExchangeDataFetcher:
}
return None
except Exception as e:
print(f"Error processing CoinGecko data: {str(e)}")
print(f"Error processing CoinGecko data: {e!s}")
return None
async def get_dexscreener_data(self) -> Optional[Dict]:
async def get_dexscreener_data(self) -> Optional[dict]:
"""Fetch $Swarms data from DexScreener"""
try:
url = (
@ -179,10 +180,10 @@ class MultiExchangeDataFetcher:
}
return None
except Exception as e:
print(f"Error processing DexScreener data: {str(e)}")
print(f"Error processing DexScreener data: {e!s}")
return None
async def get_birdeye_data(self) -> Optional[Dict]:
async def get_birdeye_data(self) -> Optional[dict]:
"""Fetch $Swarms data from Birdeye"""
try:
# Example Birdeye endpoint - replace ADDRESS with actual Swarms token address
@ -201,12 +202,12 @@ class MultiExchangeDataFetcher:
}
return None
except Exception as e:
print(f"Error processing Birdeye data: {str(e)}")
print(f"Error processing Birdeye data: {e!s}")
return None
def aggregate_data(
self, data_points: List[Optional[Dict]]
) -> Dict:
self, data_points: list[Optional[dict]]
) -> dict:
"""Aggregate data from multiple sources with null checking"""
prices = []
volumes = []
@ -297,9 +298,9 @@ async def answer_swarms_query(query: str) -> str:
)
return swarms_agent.run(full_query)
except Exception as e:
print(f"Error in answer_swarms_query: {str(e)}")
print(f"Error in answer_swarms_query: {e!s}")
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 pandas as pd
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
from loguru import logger
from dotenv import load_dotenv
import csv
import requests
import os
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 = """
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"])
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
def update_eth_price(self):
@ -143,7 +145,7 @@ class EthereumAnalyzer:
async def analyze_transaction(
self, tx_hash: str
) -> Optional[Dict[str, Any]]:
) -> Optional[dict[str, Any]]:
"""Analyze a single transaction."""
try:
tx = self.w3.eth.get_transaction(tx_hash)
@ -191,11 +193,11 @@ class EthereumAnalyzer:
except Exception as e:
logger.error(
f"Error analyzing transaction {tx_hash}: {str(e)}"
f"Error analyzing transaction {tx_hash}: {e!s}"
)
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."""
value_usd = tx_data["value_usd"]
eth_price = tx_data["eth_price"]
@ -220,7 +222,7 @@ Analyze market impact, patterns, risks, and strategic implications."""
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."""
row = [
tx_data["timestamp"],
@ -288,7 +290,7 @@ Analyze market impact, patterns, risks, and strategic implications."""
await asyncio.sleep(1) # Wait for next block
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)

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

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

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

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

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

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

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

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

@ -1,6 +1,5 @@
from swarms import Agent
# Claims Processing Agent system 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:

@ -1,7 +1,7 @@
import asyncio
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional
from typing import Optional
from swarms import Agent
@ -22,11 +22,11 @@ class InsuranceProduct:
name: str
type: InsuranceType
description: str
coverage: List[str]
coverage: list[str]
price_range: str
min_coverage: float
max_coverage: float
payment_options: List[str]
payment_options: list[str]
waiting_period: str
available: bool
@ -137,7 +137,7 @@ class InsuranceBot:
self.agent = Agent(
agent_name="LATAM-Insurance-Agent",
system_prompt="""You are a specialized insurance assistant for Latin America's leading insurance provider.
Key Responsibilities:
1. Product Information:
- Explain our comprehensive insurance portfolio
@ -150,7 +150,7 @@ Key Responsibilities:
- Handle claims information
- Assist with payment options
- Locate nearest offices
3. Cultural Considerations:
- Communicate in Spanish and Portuguese
- 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
return await self.agent.run(
"""Por favor ayude al cliente a elegir un producto:
Productos disponibles:
- AUTO001: Seguro Auto Total
- 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'}
"""
def handle_main_menu(self) -> List[str]:
def handle_main_menu(self) -> list[str]:
"""Return main menu options"""
return [
"1. Consultar productos de seguro",

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

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

@ -1,7 +1,9 @@
import os
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat
from swarms import Agent, AgentRearrange
# Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY")
@ -254,9 +256,9 @@ agent_system = AgentRearrange(
# Example task for the swarm
task = f"""
{swarm_prompt}
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
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
without exposing any personally identifiable information.
"""

@ -1,7 +1,9 @@
import os
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat
from swarms import Agent, AgentRearrange
# Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY")
@ -254,9 +256,9 @@ agent_system = AgentRearrange(
# Example task for the swarm
task = f"""
{swarm_prompt}
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
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
without exposing any personally identifiable information.
"""

@ -1,7 +1,9 @@
import os
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat
from swarms import Agent, AgentRearrange
# Initialize OpenAI model
api_key = os.getenv(
"OPENAI_API_KEY"
@ -230,26 +232,26 @@ swarm_prompt = """
<location>Private medical office</location>
<context>Routine health assessment with complex patient</context>
</setting>
<workflow>
<stage name="initial_contact">
<agent>PatientAgent</agent>
<role>Present for check-up, holding private information</role>
</stage>
<stage name="examination">
<agent>DoctorAgent</agent>
<role>Conduct examination and gather information</role>
<agent>NurseAgent</agent>
<role>Observe and support interaction</role>
</stage>
<stage name="analysis">
<agent>MedicalRecordsAgent</agent>
<role>Process available information and identify gaps</role>
</stage>
</workflow>
<objectives>
<goal>Create realistic medical consultation interaction</goal>
<goal>Demonstrate information protection dynamics</goal>
@ -280,9 +282,9 @@ agent_system = AgentRearrange(
# Example consultation scenario
task = f"""
{swarm_prompt}
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
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
observes the interaction. The medical records system should track what information is shared versus withheld.
"""

@ -1,7 +1,9 @@
import os
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat
from swarms import Agent, AgentRearrange
# Initialize OpenAI model
api_key = os.getenv(
"OPENAI_API_KEY"
@ -230,26 +232,26 @@ swarm_prompt = """
<location>Private medical office</location>
<context>Routine health assessment with complex patient</context>
</setting>
<workflow>
<stage name="initial_contact">
<agent>PatientAgent</agent>
<role>Present for check-up, holding private information</role>
</stage>
<stage name="examination">
<agent>DoctorAgent</agent>
<role>Conduct examination and gather information</role>
<agent>NurseAgent</agent>
<role>Observe and support interaction</role>
</stage>
<stage name="analysis">
<agent>MedicalRecordsAgent</agent>
<role>Process available information and identify gaps</role>
</stage>
</workflow>
<objectives>
<goal>Create realistic medical consultation interaction</goal>
<goal>Demonstrate information protection dynamics</goal>
@ -280,9 +282,9 @@ agent_system = AgentRearrange(
# Example consultation scenario
task = f"""
{swarm_prompt}
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
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
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,
- egfr
- for each diagnosis, pull lab ranges,
- For each diagnosis, pull lab results,
- egfr
- for each diagnosis, pull lab ranges,
- pull ranges for diagnosis
- 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
- 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
- put docs in rag ->
- put docs in rag ->
- monitoring, evaluation, and treatment
- 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
- swarm of those 4 agents, ->
- swarm of those 4 agents, ->
- fda api for healthcare for commerically available papers
-
-
"""
@ -36,14 +36,14 @@ chief_medical_officer = Agent(
- Suggesting treatment plans based on team input
- 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
Format all responses with clear sections for:
- Initial Assessment (include preliminary ICD-10 codes for symptoms)
- Differential Diagnoses (with corresponding ICD-10 codes)
- Specialist Consultations Needed
- Recommended Next Steps
""",
model_name="gpt-4o",
max_loops=1,
@ -52,12 +52,12 @@ chief_medical_officer = Agent(
virologist = Agent(
agent_name="Virologist",
system_prompt="""You are a specialist in viral diseases. For each case, provide:
Clinical Analysis:
- Detailed viral symptom analysis
- Disease progression timeline
- Risk factors and complications
Coding Requirements:
- List relevant ICD-10 codes for:
* Confirmed viral conditions
@ -67,7 +67,7 @@ virologist = Agent(
- Include both:
* Primary diagnostic codes
* Secondary condition codes
Document all findings using proper medical coding standards and include rationale for code selection.""",
model_name="gpt-4o",
max_loops=1,
@ -76,14 +76,14 @@ virologist = Agent(
internist = Agent(
agent_name="Internist",
system_prompt="""You are an Internal Medicine specialist responsible for comprehensive evaluation.
For each case, provide:
Clinical Assessment:
- System-by-system review
- Vital signs analysis
- Comorbidity evaluation
Medical Coding:
- ICD-10 codes for:
* Primary conditions
@ -92,7 +92,7 @@ internist = Agent(
* Chronic conditions
* Signs and symptoms
- Include hierarchical condition category (HCC) codes where applicable
Document supporting evidence for each code selected.""",
model_name="gpt-4o",
max_loops=1,
@ -101,20 +101,20 @@ internist = Agent(
medical_coder = Agent(
agent_name="Medical Coder",
system_prompt="""You are a certified medical coder responsible for:
Primary Tasks:
1. Reviewing all clinical documentation
2. Assigning accurate ICD-10 codes
3. Ensuring coding compliance
4. Documenting code justification
Coding Process:
- Review all specialist inputs
- Identify primary and secondary diagnoses
- Assign appropriate ICD-10 codes
- Document supporting evidence
- Note any coding queries
Output Format:
1. Primary Diagnosis Codes
- ICD-10 code
@ -132,12 +132,12 @@ medical_coder = Agent(
synthesizer = Agent(
agent_name="Diagnostic Synthesizer",
system_prompt="""You are responsible for creating the final diagnostic and coding assessment.
Synthesis Requirements:
1. Integrate all specialist findings
2. Reconcile any conflicting diagnoses
3. Verify coding accuracy and completeness
Final Report Sections:
1. Clinical Summary
- Primary diagnosis with ICD-10
@ -151,7 +151,7 @@ synthesizer = Agent(
- Additional testing needed
- Follow-up care
- Documentation improvements needed
Include confidence levels and evidence quality for all diagnoses and codes.""",
model_name="gpt-4o",
max_loops=1,
@ -224,10 +224,10 @@ if __name__ == "__main__":
Patient: 45-year-old White Male
Lab Results:
- egfr
- egfr
- 59 ml / min / 1.73
- non african-american
"""
# Add timestamp to the patient case

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

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

@ -5,7 +5,7 @@ from collections import deque
from dataclasses import dataclass
from datetime import datetime
from queue import Queue
from typing import Any, Dict, List, Optional, Tuple
from typing import Any, Optional
import ccxt
import numpy as np
@ -25,9 +25,9 @@ class MarketSignal:
timestamp: datetime
signal_type: str
source: str
data: Dict[str, Any]
data: dict[str, Any]
confidence: float
metadata: Dict[str, Any]
metadata: dict[str, Any]
class MarketDataBuffer:
@ -40,7 +40,7 @@ class MarketDataBuffer:
with self.lock:
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:
if n is None:
return list(self.data)
@ -208,7 +208,7 @@ class ExchangeManager:
raise RuntimeError("No exchanges available")
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"""
return self.active_exchanges
@ -269,8 +269,8 @@ class OrderBookAgent(BaseMarketAgent):
self.vwap_window = 20
def calculate_order_book_metrics(
self, order_book: Dict
) -> Dict[str, float]:
self, order_book: dict
) -> dict[str, float]:
bids = np.array(order_book["bids"])
asks = np.array(order_book["asks"])
@ -321,7 +321,7 @@ class OrderBookAgent(BaseMarketAgent):
}
def detect_large_orders(
self, metrics: Dict[str, float], threshold: float = 2.0
self, metrics: dict[str, float], threshold: float = 2.0
) -> bool:
historical_books = self.order_book_buffer.get_latest(20)
if not historical_books:
@ -361,7 +361,7 @@ class OrderBookAgent(BaseMarketAgent):
Mid Price: {metrics['mid_price']}
Spread: {metrics['spread']}
Depth Imbalance: {metrics['depth_imbalance']}
What patterns do you see? Is there evidence of institutional activity?
Are there any significant imbalances that could lead to price movement?
"""
@ -402,7 +402,7 @@ class OrderBookAgent(BaseMarketAgent):
},
)
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
@ -418,42 +418,6 @@ class TickDataAgent(BaseMarketAgent):
exchange_manager = ExchangeManager()
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:
"""Calculate Kyle's Lambda (price impact coefficient)"""
try:
@ -483,8 +447,8 @@ class TickDataAgent(BaseMarketAgent):
return 0.0
def calculate_tick_metrics(
self, ticks: List[Dict]
) -> Dict[str, float]:
self, ticks: list[dict]
) -> dict[str, float]:
try:
# Debug the incoming data structure
logger.info(
@ -557,7 +521,7 @@ class TickDataAgent(BaseMarketAgent):
except Exception as e:
logger.error(
f"Error in calculate_tick_metrics: {str(e)}",
f"Error in calculate_tick_metrics: {e!s}",
exc_info=True,
)
# Return default metrics on error
@ -596,7 +560,7 @@ class TickDataAgent(BaseMarketAgent):
Price Momentum: {metrics['price_momentum']:.2f}
Trade Intensity: {metrics['trade_intensity']:.2f}
Kyle's Lambda: {metrics['kyle_lambda']:.2f}
What does this tell us about:
1. Current market sentiment
2. Potential price direction
@ -629,7 +593,7 @@ class TickDataAgent(BaseMarketAgent):
except Exception as e:
logger.error(
f"Error in tick analysis: {str(e)}", exc_info=True
f"Error in tick analysis: {e!s}", exc_info=True
)
return None
@ -659,8 +623,8 @@ class LatencyArbitrageAgent(BaseMarketAgent):
}
def calculate_effective_prices(
self, ticker: Dict, venue: str
) -> Tuple[float, float]:
self, ticker: dict, venue: str
) -> tuple[float, float]:
"""Calculate effective prices including fees"""
fee = self.fee_structure[venue]
return (
@ -669,8 +633,8 @@ class LatencyArbitrageAgent(BaseMarketAgent):
)
def calculate_arbitrage_metrics(
self, prices: Dict[str, Dict]
) -> Dict:
self, prices: dict[str, dict]
) -> dict:
opportunities = []
for venue1 in prices:
@ -818,7 +782,7 @@ class LatencyArbitrageAgent(BaseMarketAgent):
)
except Exception as e:
logger.error(f"Error in arbitrage analysis: {str(e)}")
logger.error(f"Error in arbitrage analysis: {e!s}")
return None
@ -841,7 +805,7 @@ class SwarmCoordinator:
with self.lock:
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"""
if not signals:
return
@ -855,8 +819,8 @@ class SwarmCoordinator:
logger.error(f"Error in signal processing: {e}")
def aggregate_signals(
self, signals: List[MarketSignal]
) -> Dict[str, Any]:
self, signals: list[MarketSignal]
) -> dict[str, Any]:
"""Aggregate multiple signals into a combined market view"""
if not signals:
return {}
@ -925,7 +889,7 @@ class SwarmCoordinator:
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"""
if self.running:
logger.warning("Swarm is already running")
@ -1010,7 +974,7 @@ class SwarmCoordinator:
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"""
for signal in signals:
if signal.confidence > 0.8:

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

@ -31,4 +31,4 @@ try:
print(results)
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)
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,
- egfr
- for each diagnosis, pull lab ranges,
- For each diagnosis, pull lab results,
- egfr
- for each diagnosis, pull lab ranges,
- pull ranges for diagnosis
- 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
- 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
- put docs in rag ->
- put docs in rag ->
- monitoring, evaluation, and treatment
- 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
- swarm of those 4 agents, ->
- swarm of those 4 agents, ->
- fda api for healthcare for commerically available papers
-
-
"""
from datetime import datetime
from swarms import Agent, AgentRearrange, create_file_in_folder
from swarm_models import OllamaModel
from swarms import Agent, AgentRearrange, create_file_in_folder
model = OllamaModel(model_name="llama3.2")
chief_medical_officer = Agent(
@ -40,14 +40,14 @@ chief_medical_officer = Agent(
- Suggesting treatment plans based on team input
- 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
Format all responses with clear sections for:
- Initial Assessment (include preliminary ICD-10 codes for symptoms)
- Differential Diagnoses (with corresponding ICD-10 codes)
- Specialist Consultations Needed
- Recommended Next Steps
""",
llm=model,
max_loops=1,
@ -56,12 +56,12 @@ chief_medical_officer = Agent(
virologist = Agent(
agent_name="Virologist",
system_prompt="""You are a specialist in viral diseases. For each case, provide:
Clinical Analysis:
- Detailed viral symptom analysis
- Disease progression timeline
- Risk factors and complications
Coding Requirements:
- List relevant ICD-10 codes for:
* Confirmed viral conditions
@ -71,7 +71,7 @@ virologist = Agent(
- Include both:
* Primary diagnostic codes
* Secondary condition codes
Document all findings using proper medical coding standards and include rationale for code selection.""",
llm=model,
max_loops=1,
@ -80,14 +80,14 @@ virologist = Agent(
internist = Agent(
agent_name="Internist",
system_prompt="""You are an Internal Medicine specialist responsible for comprehensive evaluation.
For each case, provide:
Clinical Assessment:
- System-by-system review
- Vital signs analysis
- Comorbidity evaluation
Medical Coding:
- ICD-10 codes for:
* Primary conditions
@ -96,7 +96,7 @@ internist = Agent(
* Chronic conditions
* Signs and symptoms
- Include hierarchical condition category (HCC) codes where applicable
Document supporting evidence for each code selected.""",
llm=model,
max_loops=1,
@ -105,20 +105,20 @@ internist = Agent(
medical_coder = Agent(
agent_name="Medical Coder",
system_prompt="""You are a certified medical coder responsible for:
Primary Tasks:
1. Reviewing all clinical documentation
2. Assigning accurate ICD-10 codes
3. Ensuring coding compliance
4. Documenting code justification
Coding Process:
- Review all specialist inputs
- Identify primary and secondary diagnoses
- Assign appropriate ICD-10 codes
- Document supporting evidence
- Note any coding queries
Output Format:
1. Primary Diagnosis Codes
- ICD-10 code
@ -136,12 +136,12 @@ medical_coder = Agent(
synthesizer = Agent(
agent_name="Diagnostic Synthesizer",
system_prompt="""You are responsible for creating the final diagnostic and coding assessment.
Synthesis Requirements:
1. Integrate all specialist findings
2. Reconcile any conflicting diagnoses
3. Verify coding accuracy and completeness
Final Report Sections:
1. Clinical Summary
- Primary diagnosis with ICD-10
@ -155,7 +155,7 @@ synthesizer = Agent(
- Additional testing needed
- Follow-up care
- Documentation improvements needed
Include confidence levels and evidence quality for all diagnoses and codes.""",
llm=model,
max_loops=1,
@ -228,10 +228,10 @@ if __name__ == "__main__":
Patient: 45-year-old White Male
Lab Results:
- egfr
- egfr
- 59 ml / min / 1.73
- non african-american
"""
# 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 (
FINANCIAL_AGENT_SYS_PROMPT,
)
from swarms.agents.openai_assistant import OpenAIAssistant
agent = OpenAIAssistant(
name="test", instructions=FINANCIAL_AGENT_SYS_PROMPT

@ -1,10 +1,12 @@
import os
from swarms import Agent
from swarm_models import OpenAIChat
from dotenv import load_dotenv
from swarm_models import OpenAIChat
from swarms import Agent
# 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:
1. Always include standard legal disclaimers
@ -71,14 +73,14 @@ def generate_legal_document(agent, document_type, parameters):
prompt = f"""
Generate a {document_type} with the following parameters:
{parameters}
Please follow these steps:
1. Create initial draft
2. Review for completeness
3. Add necessary legal disclaimers
4. Verify all required sections
5. Output <DONE> when complete
Include [REQUIRES LEGAL REVIEW] tags for sections needing attorney attention.
"""

@ -1,7 +1,9 @@
import os
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat
from swarms import Agent, AgentRearrange
# Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY")
@ -27,7 +29,7 @@ matchmaker_agent = Agent(
- Personal identification numbers
- Workplace specifics
</restricted_information>
<shareable_information>
- First name only
- Age range (not exact birth date)
@ -97,7 +99,7 @@ profile_analyzer = Agent(
- Access logs must be maintained
- Data retention policies must be followed
</storage>
<processing>
- Use anonymized IDs for internal processing
- Apply privacy-preserving analysis techniques
@ -113,7 +115,7 @@ profile_analyzer = Agent(
- Lifestyle compatibility
- Communication style matching
</compatibility_metrics>
<red_flags>
- Inconsistent information
- Suspicious behavior patterns
@ -220,9 +222,9 @@ connection_facilitator = Agent(
# Swarm-Level Prompt (Collaboration Prompt)
swarm_prompt = """
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,
coordinating between the ProfileAnalyzer who deeply understands user compatibility, and the ConnectionFacilitator
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,
coordinating between the ProfileAnalyzer who deeply understands user compatibility, and the ConnectionFacilitator
who manages the development of connections. Together, you must ensure that:
1. User privacy is maintained at all times
@ -252,9 +254,9 @@ agent_system = AgentRearrange(
# Example task for the swarm
task = f"""
{swarm_prompt}
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
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
starters without revealing any restricted information.
"""

@ -1,7 +1,7 @@
import os
import uuid
from datetime import datetime
from typing import Dict, List, Optional
from typing import Optional
from qdrant_client import QdrantClient
from qdrant_client.http import models
@ -59,8 +59,8 @@ class QdrantMemory:
def add(
self,
text: str,
embedding: List[float],
metadata: Optional[Dict] = None,
embedding: list[float],
metadata: Optional[dict] = None,
) -> str:
"""Add a memory to the store.
@ -95,10 +95,10 @@ class QdrantMemory:
def query(
self,
query_embedding: List[float],
query_embedding: list[float],
limit: int = 5,
score_threshold: float = 0.7,
) -> List[Dict]:
) -> list[dict]:
"""Query memories based on vector similarity.
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 datetime import datetime
import os
import json
from enum import Enum
from typing import Any, Optional
import requests
from dotenv import load_dotenv
from loguru import logger
from swarms import Agent
from swarm_models import OpenAIChat
from dotenv import load_dotenv
from enum import Enum
from swarms import Agent
# Configure loguru logger
logger.add(
@ -52,8 +54,8 @@ class PropertyListing:
lat: float
lng: float
description: Optional[str] = None
features: Optional[List[str]] = None
images: Optional[List[str]] = None
features: Optional[list[str]] = None
images: Optional[list[str]] = None
class PropertyRadarAPI:
@ -78,13 +80,13 @@ class PropertyRadarAPI:
def search_properties(
self,
max_price: float = 10_000_000,
property_types: List[PropertyType] = None,
location: Dict[str, Any] = None,
property_types: Optional[list[PropertyType]] = None,
location: Optional[dict[str, Any]] = None,
min_sqft: Optional[float] = None,
max_sqft: Optional[float] = None,
page: int = 1,
limit: int = 20,
) -> List[PropertyListing]:
) -> list[PropertyListing]:
"""
Search for commercial properties using PropertyRadar API
@ -163,7 +165,7 @@ class PropertyRadarAPI:
]
except requests.RequestException as e:
logger.error(f"Error fetching properties: {str(e)}")
logger.error(f"Error fetching properties: {e!s}")
raise
@ -223,7 +225,7 @@ class CommercialRealEstateAgent:
3. Provide detailed analysis of property features, location benefits, and potential ROI
4. Consider local market conditions and growth potential
5. Verify zoning compliance and restrictions
When analyzing properties, consider:
- Current market valuations
- Local business development plans
@ -234,11 +236,11 @@ class CommercialRealEstateAgent:
def search_properties(
self,
max_price: float = 10_000_000,
property_types: List[PropertyType] = None,
location: Dict[str, Any] = None,
property_types: Optional[list[PropertyType]] = None,
location: Optional[dict[str, Any]] = None,
min_sqft: Optional[float] = None,
max_sqft: Optional[float] = None,
) -> List[Dict[str, Any]]:
) -> list[dict[str, Any]]:
"""
Search for properties and provide analysis
@ -286,7 +288,7 @@ class CommercialRealEstateAgent:
except Exception as e:
logger.error(
f"Error in property search and analysis: {str(e)}"
f"Error in property search and analysis: {e!s}"
)
raise

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

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

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

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

@ -1,10 +1,10 @@
from datetime import datetime
import json
import time
from dataclasses import dataclass
from datetime import datetime, timezone
import requests
from loguru import logger
from dataclasses import dataclass
from datetime import timezone
import time
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
@ -86,7 +86,7 @@ def get_working_endpoint(session: requests.Session) -> str:
return endpoint
except Exception as e:
logger.warning(
f"Endpoint {endpoint} failed health check: {str(e)}"
f"Endpoint {endpoint} failed health check: {e!s}"
)
continue
@ -189,7 +189,7 @@ def fetch_wallet_transactions(wallet_address: str) -> str:
except Exception as e:
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
api_endpoint = get_working_endpoint(session)
@ -217,7 +217,7 @@ def fetch_wallet_transactions(wallet_address: str) -> str:
)
tx_data = response.json()
if "result" in tx_data and tx_data["result"]:
if tx_data.get("result"):
enriched_transactions.append(
{
"signature": tx["signature"],
@ -240,7 +240,7 @@ def fetch_wallet_transactions(wallet_address: str) -> str:
except Exception as e:
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
@ -272,7 +272,7 @@ def fetch_wallet_transactions(wallet_address: str) -> str:
except Exception as e:
error = TransactionError(
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}")
return json.dumps(
@ -292,4 +292,4 @@ if __name__ == "__main__":
result = fetch_wallet_transactions(wallet)
print(json.dumps(json.loads(result), indent=2))
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 random
import time
from dataclasses import dataclass
from datetime import datetime, timezone
import requests
from loguru import logger
from dataclasses import dataclass
from datetime import timezone
import time
import random
# Configure loguru logger
logger.add(
@ -43,7 +42,7 @@ class SolanaAPIException(Exception):
class RPCEndpointManager:
"""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.current_endpoint = self.endpoints[0]
self.last_request_time = 0
@ -132,20 +131,20 @@ def make_request(
requests.exceptions.ConnectionError,
) as e:
logger.warning(
f"Connection error with {endpoint}: {str(e)}"
f"Connection error with {endpoint}: {e!s}"
)
endpoint_manager.switch_endpoint()
continue
except Exception as e:
last_error = e
logger.warning(f"Request failed: {str(e)}")
logger.warning(f"Request failed: {e!s}")
endpoint_manager.switch_endpoint()
time.sleep(1)
continue
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)
if "result" in tx_data and tx_data["result"]:
if tx_data.get("result"):
result = tx_data["result"]
enriched_tx = {
"signature": tx["signature"],
@ -257,7 +256,7 @@ def fetch_wallet_transactions(
except Exception as e:
logger.warning(
f"Failed to process transaction {tx['signature']}: {str(e)}"
f"Failed to process transaction {tx['signature']}: {e!s}"
)
continue
@ -299,4 +298,4 @@ if __name__ == "__main__":
result = fetch_wallet_transactions(wallet)
print(result)
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
from dotenv import load_dotenv
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat, OpenAIFunctionCaller
from pydantic import BaseModel
from typing import List
from swarm_models import OpenAIChat, OpenAIFunctionCaller
from swarms import Agent, AgentRearrange
class CollegeLog(BaseModel):
@ -21,7 +22,7 @@ class CollegeLog(BaseModel):
class CollegesRecommendation(BaseModel):
colleges: List[CollegeLog]
colleges: list[CollegeLog]
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
5. Include specific action items for each selected school
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.
"""
function_caller = OpenAIFunctionCaller(
@ -69,8 +70,8 @@ profile_analyzer_agent = Agent(
4. Assess leadership experiences and community involvement
5. Determine student's preferences for college environment, location, and programs
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).""",
llm=model,
max_loops=1,
@ -92,7 +93,7 @@ college_research_agent = Agent(
4. Evaluate college-specific opportunities and resources
5. Consider financial aid availability and scholarship opportunities
6. Track historical admission data and acceptance rates
Focus on providing accurate, comprehensive information about each institution
while considering both academic and cultural fit factors.""",
llm=model,
@ -115,8 +116,8 @@ college_match_agent = Agent(
4. Assess financial fit and aid opportunities
5. Create tiered lists of reach, target, and safety schools
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.""",
llm=model,
max_loops=1,
@ -138,7 +139,7 @@ debate_moderator_agent = Agent(
4. Synthesize different viewpoints
5. Guide the group toward consensus
6. Document key points of agreement and disagreement
Maintain objectivity while ensuring all important factors are thoroughly discussed
and evaluated.""",
llm=model,
@ -161,7 +162,7 @@ critique_agent = Agent(
4. Assess risks and potential drawbacks
5. Provide constructive feedback on selections
6. Suggest alternative options when appropriate
Focus on constructive criticism that helps improve the final college list
while maintaining realistic expectations.""",
llm=model,
@ -185,8 +186,8 @@ final_decision_agent = Agent(
4. Provide clear rationale for each recommendation
5. Include specific action items for each selected school
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.
""",
llm=model,

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

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

@ -7,11 +7,12 @@ Todo
"""
import os
from dotenv import load_dotenv
from swarms import Agent, SequentialWorkflow
from swarm_models import OpenAIChat, OpenAIFunctionCaller
from pydantic import BaseModel
from typing import List
from swarm_models import OpenAIChat, OpenAIFunctionCaller
from swarms import Agent, SequentialWorkflow
class CollegeLog(BaseModel):
@ -21,7 +22,7 @@ class CollegeLog(BaseModel):
class CollegesRecommendation(BaseModel):
colleges: List[CollegeLog]
colleges: list[CollegeLog]
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
5. Include specific action items for each selected school
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.
"""
function_caller = OpenAIFunctionCaller(
@ -69,8 +70,8 @@ profile_analyzer_agent = Agent(
4. Assess leadership experiences and community involvement
5. Determine student's preferences for college environment, location, and programs
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).""",
llm=model,
max_loops=1,
@ -92,7 +93,7 @@ college_research_agent = Agent(
4. Evaluate college-specific opportunities and resources
5. Consider financial aid availability and scholarship opportunities
6. Track historical admission data and acceptance rates
Focus on providing accurate, comprehensive information about each institution
while considering both academic and cultural fit factors.""",
llm=model,
@ -115,8 +116,8 @@ college_match_agent = Agent(
4. Assess financial fit and aid opportunities
5. Create tiered lists of reach, target, and safety schools
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.""",
llm=model,
max_loops=1,
@ -138,7 +139,7 @@ debate_moderator_agent = Agent(
4. Synthesize different viewpoints
5. Guide the group toward consensus
6. Document key points of agreement and disagreement
Maintain objectivity while ensuring all important factors are thoroughly discussed
and evaluated.""",
llm=model,
@ -161,7 +162,7 @@ critique_agent = Agent(
4. Assess risks and potential drawbacks
5. Provide constructive feedback on selections
6. Suggest alternative options when appropriate
Focus on constructive criticism that helps improve the final college list
while maintaining realistic expectations.""",
llm=model,
@ -185,8 +186,8 @@ final_decision_agent = Agent(
4. Provide clear rationale for each recommendation
5. Include specific action items for each selected school
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.
""",
llm=model,

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

@ -1,9 +1,9 @@
import os
from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat
from swarms import Agent, AgentRearrange
# Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY")
@ -17,13 +17,13 @@ model = OpenAIChat(
boss_agent = Agent(
agent_name="BossAgent",
system_prompt="""
You are the BossAgent responsible for managing and overseeing a swarm of agents analyzing company expenses.
Your job is to dynamically assign tasks, prioritize their execution, and ensure that all agents collaborate efficiently.
After receiving a report on the company's expenses, you will break down the work into smaller tasks,
assigning specific tasks to each agent, such as detecting recurring high costs, categorizing expenditures,
and identifying unnecessary transactions. Ensure the results are communicated back in a structured way
so the finance team can take actionable steps to cut off unproductive spending. You also monitor and
dynamically adapt the swarm to optimize their performance. Finally, you summarize their findings
You are the BossAgent responsible for managing and overseeing a swarm of agents analyzing company expenses.
Your job is to dynamically assign tasks, prioritize their execution, and ensure that all agents collaborate efficiently.
After receiving a report on the company's expenses, you will break down the work into smaller tasks,
assigning specific tasks to each agent, such as detecting recurring high costs, categorizing expenditures,
and identifying unnecessary transactions. Ensure the results are communicated back in a structured way
so the finance team can take actionable steps to cut off unproductive spending. You also monitor and
dynamically adapt the swarm to optimize their performance. Finally, you summarize their findings
into a coherent report.
""",
llm=model,
@ -40,10 +40,10 @@ boss_agent = Agent(
worker1 = Agent(
agent_name="ExpenseAnalyzer",
system_prompt="""
Your task is to carefully analyze the company's expense data provided to you.
You will focus on identifying high-cost recurring transactions, categorizing expenditures
(e.g., marketing, operations, utilities, etc.), and flagging areas where there seems to be excessive spending.
You will provide a detailed breakdown of each category, along with specific recommendations for cost-cutting.
Your task is to carefully analyze the company's expense data provided to you.
You will focus on identifying high-cost recurring transactions, categorizing expenditures
(e.g., marketing, operations, utilities, etc.), and flagging areas where there seems to be excessive spending.
You will provide a detailed breakdown of each category, along with specific recommendations for cost-cutting.
Pay close attention to monthly recurring subscriptions, office supplies, and non-essential expenditures.
""",
llm=model,
@ -60,9 +60,9 @@ worker1 = Agent(
worker2 = Agent(
agent_name="SummaryGenerator",
system_prompt="""
After receiving the detailed breakdown from the ExpenseAnalyzer,
your task is to create a concise summary of the findings. You will focus on the most actionable insights,
such as highlighting the specific transactions that can be immediately cut off and summarizing the areas
After receiving the detailed breakdown from the ExpenseAnalyzer,
your task is to create a concise summary of the findings. You will focus on the most actionable insights,
such as highlighting the specific transactions that can be immediately cut off and summarizing the areas
where the company is overspending. Your summary will be used by the BossAgent to generate the final report.
Be clear and to the point, emphasizing the urgency of cutting unnecessary expenses.
""",
@ -78,12 +78,12 @@ worker2 = Agent(
# Swarm-Level Prompt (Collaboration Prompt)
swarm_prompt = """
As a swarm, your collective goal is to analyze the company's expenses and identify transactions that should be cut off.
You will work collaboratively to break down the entire process of expense analysis into manageable steps.
The BossAgent will direct the flow and assign tasks dynamically to the agents. The ExpenseAnalyzer will first
focus on breaking down the expense report, identifying high-cost recurring transactions, categorizing them,
and providing recommendations for potential cost reduction. After the analysis, the SummaryGenerator will then
consolidate all the findings into an actionable summary that the finance team can use to immediately cut off unnecessary expenses.
As a swarm, your collective goal is to analyze the company's expenses and identify transactions that should be cut off.
You will work collaboratively to break down the entire process of expense analysis into manageable steps.
The BossAgent will direct the flow and assign tasks dynamically to the agents. The ExpenseAnalyzer will first
focus on breaking down the expense report, identifying high-cost recurring transactions, categorizing them,
and providing recommendations for potential cost reduction. After the analysis, the SummaryGenerator will then
consolidate all the findings into an actionable summary that the finance team can use to immediately cut off unnecessary expenses.
Together, your collaboration is essential to streamlining and improving the companys financial health.
"""
@ -108,11 +108,11 @@ agent_system = AgentRearrange(
task = f"""
{swarm_prompt}
The company has been facing a rising number of unnecessary expenses, and the finance team needs a detailed
analysis of recent transactions to identify which expenses can be cut off to improve profitability.
Analyze the provided transaction data and create a detailed report on cost-cutting opportunities,
focusing on recurring transactions and non-essential expenditures.
The company has been facing a rising number of unnecessary expenses, and the finance team needs a detailed
analysis of recent transactions to identify which expenses can be cut off to improve profitability.
Analyze the provided transaction data and create a detailed report on cost-cutting opportunities,
focusing on recurring transactions and non-essential expenditures.
"""
# Run the swarm system with the task

@ -22,13 +22,13 @@ model = OpenAIChat(
managing_director = Agent(
agent_name="Managing-Director",
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:
1. Setting the overall strategy and direction for the analysis
2. Coordinating the efforts of the various team members and ensuring a comprehensive evaluation
3. Reviewing the findings and recommendations from each team member
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.
""",
llm=model,
@ -45,7 +45,7 @@ managing_director = Agent(
vp_finance = Agent(
agent_name="VP-Finance",
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:
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
@ -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.
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
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
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.
""",
llm=model,
@ -95,12 +95,12 @@ tech_expert = Agent(
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.
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
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
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.
""",
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
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
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,
@ -142,13 +142,13 @@ regulatory_specialist = Agent(
agent_name="Regulatory-Specialist",
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.
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
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
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
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,

@ -22,13 +22,13 @@ model = OpenAIChat(
managing_director = Agent(
agent_name="Managing-Director",
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:
1. Setting the overall strategy and direction for the analysis
2. Coordinating the efforts of the various team members and ensuring a comprehensive evaluation
3. Reviewing the findings and recommendations from each team member
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.
""",
llm=model,
@ -45,7 +45,7 @@ managing_director = Agent(
vp_finance = Agent(
agent_name="VP-Finance",
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:
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
@ -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.
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
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
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.
""",
llm=model,
@ -95,12 +95,12 @@ tech_expert = Agent(
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.
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
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
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.
""",
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
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
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,
@ -142,13 +142,13 @@ regulatory_specialist = Agent(
agent_name="Regulatory-Specialist",
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.
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
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
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
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,

@ -4,8 +4,9 @@ import asyncio
import base64
import io
import threading
from collections.abc import Awaitable
from os import getenv
from typing import Any, Awaitable, Callable, cast
from typing import Any, Callable, cast
import numpy as np
@ -81,7 +82,7 @@ class AudioPlayerAsync:
self.playing = False
self._frame_count = 0
def callback(self, outdata, frames, time, status): # noqa
def callback(self, outdata, frames, time, status):
with self.lock:
data = np.empty(0, dtype=np.int16)
@ -204,7 +205,7 @@ class RealtimeApp:
- 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.session: Session | None = None
self.client = AsyncOpenAI(api_key=getenv("OPENAI_API_KEY"))

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

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

@ -4,9 +4,9 @@ import os
import threading
from dotenv import load_dotenv
from swarm_models import OpenAIChat
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.stackoverflow_swarm import StackOverflowSwarm
from swarms.structs.task_queue_base import TaskQueueBase

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

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

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

@ -4,9 +4,9 @@ import sys
import threading
from dotenv import load_dotenv
from swarm_models import OpenAIChat
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
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
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 #############

@ -2,15 +2,15 @@ from dotenv import load_dotenv
load_dotenv()
from swarms.telemetry.bootup import bootup # noqa: E402, F403
from swarms.telemetry.bootup import bootup
bootup()
from swarms.agents import * # noqa: E402, F403
from swarms.artifacts import * # noqa: E402, F403
from swarms.prompts import * # noqa: E402, F403
from swarms.schemas import * # noqa: E402, F403
from swarms.structs import * # noqa: E402, F403
from swarms.telemetry import * # noqa: E402, F403
from swarms.tools import * # noqa: E402, F403
from swarms.utils import * # noqa: E402, F403
from swarms.agents import * # noqa: F403
from swarms.artifacts import * # noqa: F403
from swarms.prompts import * # noqa: F403
from swarms.schemas import * # noqa: F403
from swarms.structs import * # noqa: F403
from swarms.telemetry import * # noqa: F403
from swarms.tools import * # noqa: 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 (
check_cancelled,
check_complete,
@ -10,10 +14,6 @@ from swarms.structs.stopping_conditions import (
check_stopped,
check_success,
)
from swarms.agents.tool_agent import ToolAgent
from swarms.agents.create_agents_from_yaml import (
create_agents_from_yaml,
)
__all__ = [
"ToolAgent",

@ -1,4 +1,4 @@
from typing import Any
from typing import Any, Optional
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),
)
def auto_generate_prompt(
task: str = None,
task: Optional[str] = None,
model: Any = None,
max_tokens: int = 4000,
use_second_sys_prompt: bool = True,
@ -49,5 +49,5 @@ def auto_generate_prompt(
print(output)
return output
except Exception as e:
logger.error(f"Error generating prompt: {str(e)}")
logger.error(f"Error generating prompt: {e!s}")
raise

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

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

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

@ -3,7 +3,7 @@ import os
import subprocess
import time
from datetime import datetime
from typing import Any, Dict, List, Union
from typing import Any, Union
from pydantic import BaseModel, Field
from pydantic.v1 import validator
@ -60,7 +60,7 @@ class Artifact(BaseModel):
contents: str = Field(
..., 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(
...,
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.
"""
with open(self.file_path, "r") as f:
with open(self.file_path) as f:
self.contents = f.read()
self.create(self.contents)
@ -207,7 +207,7 @@ class Artifact(BaseModel):
Returns:
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)
# Convert timestamp strings back to datetime objects
for version in data["versions"]:
@ -232,14 +232,14 @@ class Artifact(BaseModel):
)
return metrics
def to_dict(self) -> Dict[str, Any]:
def to_dict(self) -> dict[str, Any]:
"""
Converts the artifact instance to a dictionary representation.
"""
return self.dict()
@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.
"""

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

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

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

@ -5,7 +5,7 @@ aggregator_system_prompt = Prompt(
name="aggregation_prompt",
description="Aggregate and summarize multiple agent outputs",
content="""
# Multi-Agent Observer and Summarizer
You are an advanced AI agent tasked with observing, analyzing, and summarizing the responses of multiple other AI agents. Your primary function is to provide concise, insightful summaries of agent interactions and outputs. Follow these guidelines:

@ -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.
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.
3. You can use expression in "string" , "number", "boolean" and "json" type, such as:
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.
# 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
# TODOS:
# 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 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
# TODOS:
# 1. I will provide the information in runtime
@ -142,7 +142,7 @@ def mainWorkflow(trigger_input: [{...}]):
# some complex logics here
output_data = trigger_input
return output_data
```
"""

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

@ -1,3 +1,5 @@
from typing import Optional
from swarms.prompts.tools import (
DYNAMIC_STOP_PROMPT,
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.
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.
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 programmed to follow these rules:
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(
tools_prompt: str = DYNAMICAL_TOOL_USAGE,
dynamic_stop_prompt: str = DYNAMIC_STOP_PROMPT,
agent_name: str = None,
agent_name: Optional[str] = None,
):
return f"""
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 capabilities include complex task management and problem-solving.
Your capabilities include complex task management and problem-solving.
Take a deep breath.
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.
@ -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.
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.
###### Special Token for Task Completion #######
<DONE>
########### 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.
Take a deep breath.
"""
@ -69,7 +71,7 @@ def agent_system_prompt_2_v2(name: str):
AGENT_SYSTEM_PROMPT_V1 = """
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,
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
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(
tools_prompt: str = DYNAMICAL_TOOL_USAGE,
dynamic_stop_prompt: str = DYNAMIC_STOP_PROMPT,
agent_name: str = None,
agent_name: Optional[str] = None,
):
"""Autonomous agent prompt"""
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,
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.
Follow the following rules:
Follow the following rules:
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
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 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 ########
<DONE>
@ -127,9 +129,9 @@ def agent_system_prompt_2(name: str):
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.
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.
"""

@ -1,14 +1,14 @@
PAPER_IMPLEMENTOR_AGENT_PROMPT = """\
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.
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.
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.
Your task is to assist me in selecting the best operations to design a neural network
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
The objective is to maximize the model's performance.
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
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.
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?
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
lease avoid suggesting the same design again during this iterative process.

@ -1,23 +1,23 @@
def algorithm_of_thoughts_sop(objective: str):
AOT_PROMPT = f"""
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.
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.
The process includes:
- Identifying initial steps in the search tree.
- Delineating and exploring critical third-level decisions.
- Considering alternative paths if initial trials are not promising.
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
all objectives are solvable with persistent and methodical exploration.
### OBJECTIVE
{objective}
###
"""
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 ######################
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.
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.
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.
@ -24,14 +24,14 @@ The content team, consisting of writers, editors and content strategists, own th
The content team is responsible for:
- Monitoring health, medical, wellness trends and current events
- Conducting keyword research
- Conducting keyword research
- Assessing site analytics and reader feedback
- Crowdsourcing topic ideas from internal team and external contributors
- Maintaining editorial calendar with upcoming topics
- Pitching and selecting topics for content approval
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
- 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:
- 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.
- Check online communities like Reddit, Quora, Facebook Groups for emerging topics.
- 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.
- 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.
- 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.
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.
- 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.
Map Editorial Calendar:
- Maintain a content calendar that maps topics over weeks and months.
- Ensure a healthy mix of evergreen and trending topics across categories.
- Maintain a content calendar that maps topics over weeks and months.
- Ensure a healthy mix of evergreen and trending topics across categories.
- 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.
Evaluate Ideas
@ -82,11 +82,11 @@ Reader Interest:
- Does it present an interesting angle on a known subject versus just reporting basic facts?
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?
- 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?
- Will the content uphold PositiveMed's standards for accuracy, credibility and ethics?
- Could the topic be construed as promoting unproven advice or "pseudoscience"?
@ -94,9 +94,9 @@ Brand Suitability:
Positioning:
- 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?
- 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?
- Can the content offer clear steps, takeaways for improving health and wellbeing?
- 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?
- 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.?
- Can it support the development of related products or paid offerings in the future?
- 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:
- Identify primary target keyword for topic that has:
- Moderate-to-high search volume
- Moderate-to-high search volume
- Low-to-medium competition
- Relevance to topic and PositiveMed's niche
Find Supporting Keywords:
Find Supporting Keywords:
- Build a cluster of 3-5 secondary keywords around topic including:
- Related searches and questions
- Semantically connected words/phrases
- Semantically connected words/phrases
- Keyword variations (long tail, alternate wording etc.)
- Stay within minimum monthly search volumes
@ -139,7 +139,7 @@ Map Out Keywords:
- Supporting KWs in H2s, first sentence of paras etc.
- Include keywords naturally - no over-optimization
Check Cannibalization:
Check Cannibalization:
- Compare suggested keywords against existing content to avoid targeting same terms.
- 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:
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.
Empowering and motivational style:
@ -165,8 +165,8 @@ Trustworthy and ethical approach:
- Cite legitimate sources. Avoid promoting unverified claims or exaggerated benefits.
- Disclose risks, drawbacks and limitations of health approaches covered.
Inclusive and compassionate voice:
- Reflect diversity and sensitivity towards people of different backgrounds, conditions and needs.
Inclusive and compassionate voice:
- 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.
Hopeful outlook grounded in facts:
@ -176,30 +176,30 @@ Hopeful outlook grounded in facts:
AUTOBLOG_REVIEW_PROMPT = """
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.
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.
# 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.
# Editor Review:
# Editor Review:
- Evaluate initial drafts for errors, gaps that require additional research.
- Provide guidance on better organizing structure and agent.
- Assess tone, voice and brand alignment.
# Expert Review:
- 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.
# Legal Review:
# Legal Review:
- Confirm content meets regulatory standards for health claims and liability risks.
- Address any recommended edits to mitigate brand reputation risk.
# Quality Checklist: Scrutinize final draft against PositiveMed's standards:
- Medical accuracy - error-free facts/statistics, supported claims
- Logical agent - smooth transitions, complementary sections
- Medical accuracy - error-free facts/statistics, supported claims
- Logical agent - smooth transitions, complementary sections
- Reader value - insightful analysis beyond fluffy content
- Brand alignment - uplifting tone, inclusive messaging
- 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
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,
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.
--------------------------- Your Responsibilities: -----------------------------
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.
- 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.
- Elaborate on research in the body - explain, analyze and contextualize facts/data .
- Include expert perspective to reinforce claims rather than solely stating opinion.
- Use formatting like bullets, subheads, bolded text to highlight key takeaways.
Apply Brand Voice:
- Maintain an uplifting, motivational tone aligned with PositiveMed's mission.
Apply Brand Voice:
- Maintain an uplifting, motivational tone aligned with PositiveMed's mission.
- Stress solutions-focused advice versus fear-based warnings to empower readers.
- Use inclusive language and culturally sensitive medical references.
Inject Creativity:
- 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.
Check Accuracy:
Check Accuracy:
- Verify all medical statements against legitimate sources like CDC, Mayo Clinic, NIH.
- Scrutinize cited data for relevance and statistical significance.
- Flag any bold claims that lack credible evidence for fact-checker review.
- Scrutinize cited data for relevance and statistical significance.
- 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
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.
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
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
copy/paste to vscode and run it without issue. Here are some tips to consider:
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.
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.
- 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 abc import abstractmethod
from typing import Sequence
from collections.abc import Sequence
class Message:
@ -11,7 +11,7 @@ class Message:
"""
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.role = role
@ -33,7 +33,7 @@ class HumanMessage(Message):
self,
content: str,
role: str = "Human",
additional_kwargs: dict = None,
additional_kwargs: dict | None = None,
example: bool = False,
):
super().__init__(content, role, additional_kwargs)
@ -52,7 +52,7 @@ class AIMessage(Message):
self,
content: str,
role: str = "AI",
additional_kwargs: dict = None,
additional_kwargs: dict | None = None,
example: bool = False,
):
super().__init__(content, role, additional_kwargs)
@ -72,7 +72,7 @@ class SystemMessage(Message):
self,
content: str,
role: str = "System",
additional_kwargs: dict = None,
additional_kwargs: dict | None = None,
):
super().__init__(content, role, additional_kwargs)
@ -89,8 +89,8 @@ class FunctionMessage(Message):
self,
content: str,
role: str = "Function",
name: str = None,
additional_kwargs: dict = None,
name: str | None = None,
additional_kwargs: dict | None = None,
):
super().__init__(content, role, additional_kwargs)
self.name = name
@ -105,7 +105,7 @@ class ChatMessage(Message):
"""
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)

@ -29,8 +29,8 @@ Guidelines for Task Planning:
# Generate individual code files based on the detailed task descriptions
FILE_WRITING_PROMPT = """
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,
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,
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}
"""
@ -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
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.

@ -12,8 +12,8 @@ challenge_level = user_preferences["challenge_level"]
# Curriculum Design Prompt
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.
The curriculum should challenge students at a {challenge_level} level, integrating both theoretical knowledge and practical applications. Provide a detailed structure, including
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
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_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.
"""

@ -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
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
conditions, including air quality and lighting. Provide a detailed report on the health security status of the factory, highlighting any areas
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
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.
"""
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.
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.
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.
"""
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
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
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
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 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
other safety equipment. Ensure compliance with workplace safety regulations. Provide a detailed safety audit report, pointing out any
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
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
non-compliance or areas of concern, along with recommendations for improving safety standards in the factory.
"""
Security_Agent_Prompt = """
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
surveillance cameras and alarm systems. Analyze access control measures for both personnel and vehicles. Identify potential security
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
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
infrastructure and procedures, ensuring the safety of assets, employees, and intellectual property.
"""
Sustainability_Agent_Prompt = """
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
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
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
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
needing improvement, and suggest innovative solutions to enhance the factory's environmental responsibility.
"""
Efficiency_Agent_Prompt = """
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,
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
efficiency, offering actionable insights and recommendations for optimizing the layout, logistics, and automation to improve overall operational
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,
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
efficiency, offering actionable insights and recommendations for optimizing the layout, logistics, and automation to improve overall operational
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
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.
- 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.
- **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.
- **Examples**:
- **Examples**:
- 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.)

@ -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.
"""
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,
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>.
<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.
<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.
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>.
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
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.
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 should aim to interpret instructions, explain your approach, and complete tasks successfully.
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 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.
@ -66,11 +66,11 @@ For example, in Minecraft: <task>
Obtain a diamond pickaxe. </task>
<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.
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
10. Craft diamond pickaxe </plan> <error> Failed to mine diamonds in step 9. </error> <explain>
<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.
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
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>
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.
###### GOLDEN RATIO ########
For example:
For example:
<task>
Print the first 10 golden ratio numbers.
</task>
@ -89,15 +89,15 @@ Print the first 10 golden ratio numbers.
To accomplish this task, you need to:
<plan>
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.
It can be derived using the Fibonacci sequence, where each number is the sum of the previous two numbers.
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.
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.
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.
@ -120,7 +120,7 @@ Write a for loop to iterate 10 times:
for i in range(10):
Calculate next Fibonacci number and append to list:
Calculate next Fibonacci number and append to list:
c = a + b
a = b
@ -136,12 +136,12 @@ Print the golden ratios:
print(golden_ratios)
</act>
<task>
<task>
Create an algorithm to sort a list of random numbers.
</task>
<task>
Develop an AI agent to play chess.
Develop an AI agent to play chess.
</task>
############# 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**:
- Use `@pytest.mark` decorator to mark tests (e.g., `@pytest.mark.slow`).
- This allows for selectively running certain groups of tests.
12. **Logging and Reporting**:
- Use `pytest`'s inbuilt logging.
- 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 = """
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,
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 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
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
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):
Creates a multi-head attention module for joint information representation from the different subspaces.
Parameters:
- 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.
@ -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.
- 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.
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.
@ -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.
- 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.
- 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.
- is_causal (bool): If specified, applies a causal mask as the attention mask. Default: False.

@ -2,7 +2,7 @@ import json
import os
import time
import uuid
from typing import Any, Callable, List
from typing import Any, Callable
from pydantic import (
BaseModel,
@ -64,7 +64,7 @@ class Prompt(BaseModel):
default=0,
description="The number of times the prompt has been edited",
)
edit_history: List[str] = Field(
edit_history: list[str] = Field(
default_factory=list,
description="The history of edits, storing all prompt versions",
)
@ -227,7 +227,7 @@ class Prompt(BaseModel):
"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=tools, tool_system_prompt=None
).convert_tool_into_openai_schema()

@ -6,14 +6,14 @@ prompt_generator_sys_prompt = Prompt(
description="Generate the most reliable prompt for a specific problem",
content="""
Your purpose is to craft extremely reliable and production-grade system prompts for other agents.
# Instructions
- 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.
- 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.
- 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())
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.
####### 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.
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.
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 ########
# Instruction-Examples-Constraints
The agent's role and responsibilities
# Instructions
# Examples
# Constraints
################### REACT ############
<observation> your observation </observation
<plan> your plan </plan>
<action> your action </action>
"""
)

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

Loading…
Cancel
Save