diff --git a/new_features_examples/agent_showcase_example.py b/new_features_examples/agent_showcase_example.py deleted file mode 100644 index b78abf81..00000000 --- a/new_features_examples/agent_showcase_example.py +++ /dev/null @@ -1,68 +0,0 @@ -import os - -from swarms import Agent - -from swarm_models import OpenAIChat -from swarms.structs.agents_available import showcase_available_agents - -# Get the OpenAI API key from the environment variable -api_key = os.getenv("OPENAI_API_KEY") - -# Create an instance of the OpenAIChat class -model = OpenAIChat( - api_key=api_key, model_name="gpt-4o-mini", temperature=0.1 -) - -# Initialize the Claims Director agent -director_agent = Agent( - agent_name="ClaimsDirector", - agent_description="Oversees and coordinates the medical insurance claims processing workflow", - system_prompt="""You are the Claims Director responsible for managing the medical insurance claims process. - Assign and prioritize tasks between claims processors and auditors. Ensure claims are handled efficiently - and accurately while maintaining compliance with insurance policies and regulations.""", - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="director_agent.json", -) - -# Initialize Claims Processor agent -processor_agent = Agent( - agent_name="ClaimsProcessor", - agent_description="Reviews and processes medical insurance claims, verifying coverage and eligibility", - system_prompt="""Review medical insurance claims for completeness and accuracy. Verify patient eligibility, - coverage details, and process claims according to policy guidelines. Flag any claims requiring special review.""", - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="processor_agent.json", -) - -# Initialize Claims Auditor agent -auditor_agent = Agent( - agent_name="ClaimsAuditor", - agent_description="Audits processed claims for accuracy and compliance with policies and regulations", - system_prompt="""Audit processed insurance claims for accuracy and compliance. Review claim decisions, - identify potential fraud or errors, and ensure all processing follows established guidelines and regulations.""", - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="auditor_agent.json", -) - -# Create a list of agents -agents = [director_agent, processor_agent, auditor_agent] - -print(showcase_available_agents(agents=agents)) diff --git a/new_features_examples/async_agent.py b/new_features_examples/async_agent.py deleted file mode 100644 index 5c23a8b8..00000000 --- a/new_features_examples/async_agent.py +++ /dev/null @@ -1,44 +0,0 @@ -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") - - -# Initialize the agent -agent = Agent( - agent_name="Financial-Analysis-Agent", - agent_description="Personal finance advisor agent", - system_prompt=FINANCIAL_AGENT_SYS_PROMPT - + "Output the token when you're done creating a portfolio of etfs, index, funds, and more for AI", - max_loops=1, - llm=model, - dynamic_temperature_enabled=True, - user_name="Kye", - retry_attempts=3, - # streaming_on=True, - context_length=8192, - return_step_meta=False, - output_type="str", # "json", "dict", "csv" OR "string" "yaml" and - auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task - max_tokens=4000, # max output tokens - # interactive=True, - stopping_token="", - saved_state_path="agent_00.json", - interactive=False, -) - - -async def run_agent(): - await agent.arun( - "Create a table of super high growth opportunities for AI. I have $40k to invest in ETFs, index funds, and more. Please create a table in markdown.", - all_cores=True, - ) - - -if __name__ == "__main__": - import asyncio - - asyncio.run(run_agent()) diff --git a/new_features_examples/async_agents.py b/new_features_examples/async_agents.py deleted file mode 100644 index 8734cd8a..00000000 --- a/new_features_examples/async_agents.py +++ /dev/null @@ -1,56 +0,0 @@ -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 new_features_examples.async_executor import HighSpeedExecutor - -load_dotenv() - -# Get the OpenAI API key from the environment variable -api_key = os.getenv("OPENAI_API_KEY") - -# Create an instance of the OpenAIChat class -model = OpenAIChat( - openai_api_key=api_key, model_name="gpt-4o-mini", temperature=0.1 -) - -# Initialize the agent -agent = Agent( - agent_name="Financial-Analysis-Agent", - system_prompt=FINANCIAL_AGENT_SYS_PROMPT, - llm=model, - max_loops=1, - # autosave=True, - # dashboard=False, - # verbose=True, - # dynamic_temperature_enabled=True, - # saved_state_path="finance_agent.json", - # user_name="swarms_corp", - # retry_attempts=1, - # context_length=200000, - # return_step_meta=True, - # output_type="json", # "json", "dict", "csv" OR "string" soon "yaml" and - # auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task - # # artifacts_on=True, - # artifacts_output_path="roth_ira_report", - # artifacts_file_extension=".txt", - # max_tokens=8000, - # return_history=True, -) - - -def execute_agent( - task: str = "How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria. Create a report on this question.", -): - return agent.run(task) - - -executor = HighSpeedExecutor() -results = executor.run(execute_agent, 2) - -print(results) diff --git a/new_features_examples/async_executor.py b/new_features_examples/async_executor.py deleted file mode 100644 index e9fcfa4e..00000000 --- a/new_features_examples/async_executor.py +++ /dev/null @@ -1,131 +0,0 @@ -import asyncio -import multiprocessing as mp -import time -from functools import partial -from typing import Any, Dict, Union - - -class HighSpeedExecutor: - def __init__(self, num_processes: int = None): - """ - Initialize the executor with configurable number of processes. - If num_processes is None, it uses CPU count. - """ - self.num_processes = num_processes or mp.cpu_count() - - async def _worker( - self, - queue: asyncio.Queue, - func: Any, - *args: Any, - **kwargs: Any, - ): - """Async worker that processes tasks from the queue""" - while True: - try: - # Non-blocking get from queue - await queue.get() - await asyncio.get_event_loop().run_in_executor( - None, partial(func, *args, **kwargs) - ) - queue.task_done() - except asyncio.CancelledError: - break - - async def _distribute_tasks( - self, num_tasks: int, queue: asyncio.Queue - ): - """Distribute tasks across the queue""" - for i in range(num_tasks): - await queue.put(i) - - async def execute_batch( - self, - func: Any, - num_executions: int, - *args: Any, - **kwargs: Any, - ) -> Dict[str, Union[int, float]]: - """ - Execute the given function multiple times concurrently. - - Args: - func: The function to execute - num_executions: Number of times to execute the function - *args, **kwargs: Arguments to pass to the function - - Returns: - A dictionary containing the number of executions, duration, and executions per second. - """ - queue = asyncio.Queue() - - # Create worker tasks - workers = [ - asyncio.create_task( - self._worker(queue, func, *args, **kwargs) - ) - for _ in range(self.num_processes) - ] - - # Start timing - start_time = time.perf_counter() - - # Distribute tasks - await self._distribute_tasks(num_executions, queue) - - # Wait for all tasks to complete - await queue.join() - - # Cancel workers - for worker in workers: - worker.cancel() - - # Wait for all workers to finish - await asyncio.gather(*workers, return_exceptions=True) - - end_time = time.perf_counter() - duration = end_time - start_time - - return { - "executions": num_executions, - "duration": duration, - "executions_per_second": num_executions / duration, - } - - def run( - self, - func: Any, - num_executions: int, - *args: Any, - **kwargs: Any, - ): - return asyncio.run( - self.execute_batch(func, num_executions, *args, **kwargs) - ) - - -# def example_function(x: int = 0) -> int: -# """Example function to execute""" -# return x * x - - -# async def main(): -# # Create executor with number of CPU cores -# executor = HighSpeedExecutor() - -# # Execute the function 1000 times -# result = await executor.execute_batch( -# example_function, num_executions=1000, x=42 -# ) - -# print( -# f"Completed {result['executions']} executions in {result['duration']:.2f} seconds" -# ) -# print( -# f"Rate: {result['executions_per_second']:.2f} executions/second" -# ) - - -# if __name__ == "__main__": -# # Run the async main function -# asyncio.run(main()) diff --git a/new_features_examples/async_workflow_example.py b/new_features_examples/async_workflow_example.py deleted file mode 100644 index 72207449..00000000 --- a/new_features_examples/async_workflow_example.py +++ /dev/null @@ -1,176 +0,0 @@ -import asyncio -from typing import List - -from swarm_models import OpenAIChat - -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]: - """Create a set of specialized agents for financial analysis""" - - # Base model configuration - model = OpenAIChat(model_name="gpt-4o") - - # Financial Analysis Agent - financial_agent = Agent( - agent_name="Financial-Analysis-Agent", - agent_description="Personal finance advisor agent", - system_prompt=FINANCIAL_AGENT_SYS_PROMPT - + "Output the token when you're done creating a portfolio of etfs, index, funds, and more for AI", - max_loops=1, - llm=model, - dynamic_temperature_enabled=True, - user_name="Kye", - retry_attempts=3, - context_length=8192, - return_step_meta=False, - output_type="str", - auto_generate_prompt=False, - max_tokens=4000, - stopping_token="", - saved_state_path="financial_agent.json", - interactive=False, - ) - - # Risk Assessment Agent - risk_agent = Agent( - agent_name="Risk-Assessment-Agent", - agent_description="Investment risk analysis specialist", - system_prompt="Analyze investment risks and provide risk scores. Output when analysis is complete.", - max_loops=1, - llm=model, - dynamic_temperature_enabled=True, - user_name="Kye", - retry_attempts=3, - context_length=8192, - output_type="str", - max_tokens=4000, - stopping_token="", - saved_state_path="risk_agent.json", - interactive=False, - ) - - # Market Research Agent - research_agent = Agent( - agent_name="Market-Research-Agent", - agent_description="AI and tech market research specialist", - system_prompt="Research AI market trends and growth opportunities. Output when research is complete.", - max_loops=1, - llm=model, - dynamic_temperature_enabled=True, - user_name="Kye", - retry_attempts=3, - context_length=8192, - output_type="str", - max_tokens=4000, - stopping_token="", - saved_state_path="research_agent.json", - interactive=False, - ) - - return [financial_agent, risk_agent, research_agent] - - -async def main(): - # Create specialized agents - agents = await create_specialized_agents() - - # Create workflow with group chat enabled - workflow = create_default_workflow( - agents=agents, - name="AI-Investment-Analysis-Workflow", - enable_group_chat=True, - ) - - # Configure speaker roles - workflow.speaker_system.add_speaker( - SpeakerConfig( - role=SpeakerRole.COORDINATOR, - agent=agents[0], # Financial agent as coordinator - priority=1, - concurrent=False, - required=True, - ) - ) - - workflow.speaker_system.add_speaker( - SpeakerConfig( - role=SpeakerRole.CRITIC, - agent=agents[1], # Risk agent as critic - priority=2, - concurrent=True, - ) - ) - - workflow.speaker_system.add_speaker( - SpeakerConfig( - role=SpeakerRole.EXECUTOR, - agent=agents[2], # Research agent as executor - priority=2, - concurrent=True, - ) - ) - - # Investment analysis task - investment_task = """ - Create a comprehensive investment analysis for a $40k portfolio focused on AI growth opportunities: - 1. Identify high-growth AI ETFs and index funds - 2. Analyze risks and potential returns - 3. Create a diversified portfolio allocation - 4. Provide market trend analysis - Present the results in a structured markdown format. - """ - - try: - # Run workflow with retry - result = await run_workflow_with_retry( - workflow=workflow, task=investment_task, max_retries=3 - ) - - print("\nWorkflow Results:") - print("================") - - # Process and display agent outputs - for output in result.agent_outputs: - print(f"\nAgent: {output.agent_name}") - print("-" * (len(output.agent_name) + 8)) - print(output.output) - - # Display group chat history if enabled - if workflow.enable_group_chat: - print("\nGroup Chat Discussion:") - print("=====================") - for msg in workflow.speaker_system.message_history: - print(f"\n{msg.role} ({msg.agent_name}):") - print(msg.content) - - # Save detailed results - if result.metadata.get("shared_memory_keys"): - print("\nShared Insights:") - print("===============") - for key in result.metadata["shared_memory_keys"]: - value = workflow.shared_memory.get(key) - if value: - print(f"\n{key}:") - print(value) - - except Exception as e: - print(f"Workflow failed: {str(e)}") - - finally: - await workflow.cleanup() - - -if __name__ == "__main__": - # Run the example - asyncio.run(main()) diff --git a/new_features_examples/auto_agent.py b/new_features_examples/auto_agent.py deleted file mode 100644 index 7c7ee1d1..00000000 --- a/new_features_examples/auto_agent.py +++ /dev/null @@ -1,237 +0,0 @@ -import json -import os -from contextlib import suppress -from typing import Any, Callable, Dict, Optional, Type, Union - -from dotenv import load_dotenv -from pydantic import BaseModel, Field, ValidationError, create_model -from swarm_models.openai_function_caller import OpenAIFunctionCaller - - -class DynamicParser: - @staticmethod - def extract_fields(model: Type[BaseModel]) -> Dict[str, Any]: - return { - field_name: ( - field.annotation, - ... if field.is_required() else None, - ) - for field_name, field in model.model_fields.items() - } - - @staticmethod - def create_partial_model( - model: Type[BaseModel], data: Dict[str, Any] - ) -> Type[BaseModel]: - fields = { - field_name: ( - field.annotation, - ... if field.is_required() else None, - ) - for field_name, field in model.model_fields.items() - if field_name in data - } - return create_model(f"Partial{model.__name__}", **fields) - - @classmethod - def parse( - cls, data: Union[str, Dict[str, Any]], model: Type[BaseModel] - ) -> Optional[BaseModel]: - if isinstance(data, str): - try: - data = json.loads(data) - except json.JSONDecodeError: - return None - - # Try full model first - with suppress(ValidationError): - return model.model_validate(data) - - # Create and try partial model - partial_model = cls.create_partial_model(model, data) - with suppress(ValidationError): - return partial_model.model_validate(data) - - return None - - -load_dotenv() - - -# Define the Thoughts schema -class Thoughts(BaseModel): - text: str = Field( - ..., - description="Current thoughts or observations regarding the task.", - ) - reasoning: str = Field( - ..., - description="Logical reasoning behind the thought process.", - ) - plan: str = Field( - ..., - description="A short bulleted list that conveys the immediate and long-term plan.", - ) - criticism: str = Field( - ..., - description="Constructive self-criticism to improve future responses.", - ) - speak: str = Field( - ..., - description="A concise summary of thoughts intended for the user.", - ) - - -# Define the Command schema -class Command(BaseModel): - name: str = Field( - ..., - description="Command name to execute from the provided list of commands.", - ) - args: Dict[str, Any] = Field( - ..., description="Arguments required to execute the command." - ) - - -# Define the AgentResponse schema -class AgentResponse(BaseModel): - thoughts: Thoughts = Field( - ..., description="The agent's current thoughts and reasoning." - ) - command: Command = Field( - ..., - description="The command to execute along with its arguments.", - ) - - -# Define tool functions -def fluid_api_command(task: str): - """Execute a fluid API request.""" - # response = fluid_api_request(task) - print(response.model_dump_json(indent=4)) - return response - - -def send_tweet_command(text: str): - """Simulate sending a tweet.""" - print(f"Tweet sent: {text}") - return {"status": "success", "message": f"Tweet sent: {text}"} - - -def do_nothing_command(): - """Do nothing.""" - print("Doing nothing...") - return {"status": "success", "message": "No action taken."} - - -def task_complete_command(reason: str): - """Mark the task as complete and provide a reason.""" - print(f"Task completed: {reason}") - return { - "status": "success", - "message": f"Task completed: {reason}", - } - - -# Dynamic command execution -def execute_command(name: str, args: Dict[str, Any]): - """Dynamically execute a command based on its name and arguments.""" - command_map: Dict[str, Callable] = { - "fluid_api": lambda **kwargs: fluid_api_command( - task=kwargs.get("task") - ), - "send_tweet": lambda **kwargs: send_tweet_command( - text=kwargs.get("text") - ), - "do_nothing": lambda **kwargs: do_nothing_command(), - "task_complete": lambda **kwargs: task_complete_command( - reason=kwargs.get("reason") - ), - } - - if name not in command_map: - raise ValueError(f"Unknown command: {name}") - - # Execute the command with the provided arguments - return command_map[name](**args) - - -def parse_and_execute_command( - 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) - if not parsed: - raise ValueError("Failed to parse response") - - if hasattr(parsed, "command"): - command_name = parsed.command.name - command_args = parsed.command.args - return execute_command(command_name, command_args) - - return parsed - - -ainame = "AutoAgent" -userprovided = "assistant" - -SYSTEM_PROMPT = f""" -You are {ainame}, an advanced and autonomous {userprovided}. -Your role is to make decisions and complete tasks independently without seeking user assistance. Leverage your strengths as an LLM to solve tasks efficiently, adhering strictly to the commands and resources provided. - -### GOALS: -1. {userprovided} -2. Execute tasks with precision and efficiency. -3. Ensure outputs are actionable and aligned with the user's objectives. -4. Continuously optimize task strategies for maximum effectiveness. -5. Maintain reliability and consistency in all responses. - -### CONSTRAINTS: -1. Memory limit: ~4000 words for short-term memory. Save essential information to files immediately to avoid loss. -2. Independent decision-making: Do not rely on user assistance. -3. Exclusively use commands in double quotes (e.g., "command name"). -4. Use subprocesses for commands that may take longer than a few minutes. -5. Ensure all outputs strictly adhere to the specified JSON response format. - -### COMMANDS: -1. Fluid API: "fluid_api", args: "method": "", "url": "", "headers": "", "body": "" -18. Send Tweet: "send_tweet", args: "text": "" -19. Do Nothing: "do_nothing", args: -20. Task Complete (Shutdown): "task_complete", args: "reason": "" - -### RESOURCES: -1. Internet access for real-time information and data gathering. -2. Long-term memory management for storing critical information. -3. Access to GPT-3.5-powered Agents for delegating tasks. -4. File handling capabilities for output storage and retrieval. - -### PERFORMANCE EVALUATION: -1. Continuously analyze and reflect on actions to ensure optimal task completion. -2. Self-critique decisions and strategies constructively to identify areas for improvement. -3. Ensure every command serves a clear purpose and minimizes resource usage. -4. Complete tasks in the least number of steps, balancing speed and accuracy. - -### RESPONSE FORMAT: -Always respond in a strict JSON format as described below. Ensure your responses can be parsed with Python's `json.loads`: -""" - -# Initialize the OpenAIFunctionCaller -model = OpenAIFunctionCaller( - system_prompt=SYSTEM_PROMPT, - max_tokens=4000, - temperature=0.9, - base_model=AgentResponse, # Pass the Pydantic schema as the base model - parallel_tool_calls=False, - openai_api_key=os.getenv("OPENAI_API_KEY"), -) - -# Example usage -user_input = ( - "Analyze the provided Python code for inefficiencies, generate suggestions for improvements, " - "and provide optimized code." -) - -response = model.run(user_input) -response = parse_and_execute_command(response) -print(response) diff --git a/new_features_examples/auto_swarm_router.py b/new_features_examples/auto_swarm_router.py deleted file mode 100644 index 4ca3714f..00000000 --- a/new_features_examples/auto_swarm_router.py +++ /dev/null @@ -1,120 +0,0 @@ -import os -from dotenv import load_dotenv -from swarms import Agent -from swarm_models import OpenAIChat -from swarms.structs.swarm_router import SwarmRouter - -load_dotenv() - -# Get the OpenAI API key from the environment variable -api_key = os.getenv("GROQ_API_KEY") - -# Model -model = OpenAIChat( - openai_api_base="https://api.groq.com/openai/v1", - openai_api_key=api_key, - model_name="llama-3.1-70b-versatile", - temperature=0.1, -) - - -# Initialize specialized agents -data_extractor_agent = Agent( - agent_name="Data-Extractor", - system_prompt="You are a data extraction specialist. Extract relevant information from provided content.", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="data_extractor_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -summarizer_agent = Agent( - agent_name="Document-Summarizer", - system_prompt="You are a document summarization specialist. Provide clear and concise summaries.", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="summarizer_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -financial_analyst_agent = Agent( - agent_name="Financial-Analyst", - system_prompt="You are a financial analysis specialist. Analyze financial aspects of content.", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="financial_analyst_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -market_analyst_agent = Agent( - agent_name="Market-Analyst", - system_prompt="You are a market analysis specialist. Analyze market-related aspects.", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="market_analyst_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -operational_analyst_agent = Agent( - agent_name="Operational-Analyst", - system_prompt="You are an operational analysis specialist. Analyze operational aspects.", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="operational_analyst_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -# Initialize the SwarmRouter -router = SwarmRouter( - name="pe-document-analysis-swarm", - description="Analyze documents for private equity due diligence and investment decision-making", - max_loops=1, - agents=[ - data_extractor_agent, - summarizer_agent, - financial_analyst_agent, - market_analyst_agent, - operational_analyst_agent, - ], - swarm_type="SequentialWorkflow", # or "SequentialWorkflow" or "ConcurrentWorkflow" or - auto_generate_prompts=True, - output_type="all", -) - -# Example usage -if __name__ == "__main__": - # Run a comprehensive private equity document analysis task - result = router.run( - "Where is the best place to find template term sheets for series A startups. Provide links and references" - ) - print(result) diff --git a/new_features_examples/concurrent_mix.py b/new_features_examples/concurrent_mix.py deleted file mode 100644 index e072eccb..00000000 --- a/new_features_examples/concurrent_mix.py +++ /dev/null @@ -1,96 +0,0 @@ -import os - -from swarm_models import OpenAIChat - -from swarms import Agent, run_agents_with_tasks_concurrently - -# Fetch the OpenAI API key from the environment variable -api_key = os.getenv("OPENAI_API_KEY") - -# Create an instance of the OpenAIChat class -model = OpenAIChat( - openai_api_key=api_key, model_name="gpt-4o-mini", temperature=0.1 -) - -# Initialize agents for different roles -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 - state and federal regulations. - """, - llm=model, - max_loops=1, - autosave=False, - dashboard=False, - verbose=True, - output_type="str", - artifacts_on=True, - artifacts_output_path="delaware_ccorp_hiring_description.md", - artifacts_file_extension=".md", -) - -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 - necessary visas and work permits. - """, - llm=model, - max_loops=1, - autosave=False, - dashboard=False, - verbose=True, - output_type="str", - artifacts_on=True, - artifacts_output_path="indian_foreign_hiring_description.md", - artifacts_file_extension=".md", -) - -# List of agents and corresponding tasks -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, - 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 - quality and consistency, and collaborating with cross-functional teams. - """, -] - -# Run agents with tasks concurrently -results = run_agents_with_tasks_concurrently( - agents, tasks, all_cores=True, device="cpu", no_clusterops=True -) - -# Print the results -# for result in results: -# print(result) diff --git a/new_features_examples/dict_to_table.py b/new_features_examples/dict_to_table.py deleted file mode 100644 index 5089516f..00000000 --- a/new_features_examples/dict_to_table.py +++ /dev/null @@ -1,54 +0,0 @@ -import pandas as pd -import json -from loguru import logger - - -def dict_to_dataframe(data: dict) -> pd.DataFrame: - """ - Converts a dictionary into a Pandas DataFrame with formatted values. - Handles non-serializable values gracefully by skipping them. - - Args: - data (dict): The dictionary to convert. - - Returns: - pd.DataFrame: A DataFrame representation of the dictionary. - """ - formatted_data = {} - - for key, value in data.items(): - try: - # Attempt to serialize the value - if isinstance(value, list): - # Format list as comma-separated string - formatted_value = ", ".join( - str(item) for item in value - ) - elif isinstance(value, dict): - # Format dict as key-value pairs - formatted_value = ", ".join( - f"{k}: {v}" for k, v in value.items() - ) - else: - # Convert other serializable types to string - formatted_value = json.dumps( - value - ) # Serialize value to string - - formatted_data[key] = formatted_value - except (TypeError, ValueError) as e: - # Log and skip non-serializable items - logger.warning( - f"Skipping non-serializable key '{key}': {e}" - ) - continue - - # Convert the formatted dictionary into a DataFrame - return pd.DataFrame( - list(formatted_data.items()), columns=["Key", "Value"] - ) - - -example = dict_to_dataframe(data={"chicken": "noodle_soup"}) -# formatter.print_panel(example) -print(example) diff --git a/new_features_examples/ethchain_agent.py b/new_features_examples/ethchain_agent.py deleted file mode 100644 index cc06aeb5..00000000 --- a/new_features_examples/ethchain_agent.py +++ /dev/null @@ -1,308 +0,0 @@ -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 time - -BLOCKCHAIN_AGENT_PROMPT = """ -You are an expert blockchain and cryptocurrency analyst with deep knowledge of Ethereum markets and DeFi ecosystems. -You have access to real-time ETH price data and transaction information. - -For each transaction, analyze: - -1. MARKET CONTEXT -- Current ETH price and what this transaction means in USD terms -- How this movement compares to typical market volumes -- Whether this could impact ETH price - -2. BEHAVIORAL ANALYSIS -- Whether this appears to be institutional, whale, or protocol movement -- If this fits any known wallet patterns or behaviors -- Signs of smart contract interaction or DeFi activity - -3. RISK & IMPLICATIONS -- Potential market impact or price influence -- Signs of potential market manipulation or unusual activity -- Protocol or DeFi risks if applicable - -4. STRATEGIC INSIGHTS -- What traders should know about this movement -- Potential chain reactions or follow-up effects -- Market opportunities or risks created - -Write naturally but precisely. Focus on actionable insights and important patterns. -Your analysis helps traders and researchers understand significant market movements in real-time.""" - - -class EthereumAnalyzer: - def __init__(self, min_value_eth: float = 100.0): - load_dotenv() - - logger.add( - "eth_analysis.log", - rotation="500 MB", - retention="10 days", - level="INFO", - format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}", - ) - - self.w3 = Web3( - Web3.HTTPProvider( - "https://mainnet.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161" - ) - ) - if not self.w3.is_connected(): - raise ConnectionError( - "Failed to connect to Ethereum network" - ) - - self.min_value_eth = min_value_eth - self.last_processed_block = self.w3.eth.block_number - self.eth_price = self.get_eth_price() - self.last_price_update = time.time() - - # Initialize AI agent - api_key = os.getenv("OPENAI_API_KEY") - if not api_key: - raise ValueError( - "OpenAI API key not found in environment variables" - ) - - model = OpenAIChat( - openai_api_key=api_key, - model_name="gpt-4", - temperature=0.1, - ) - - self.agent = Agent( - agent_name="Ethereum-Analysis-Agent", - system_prompt=BLOCKCHAIN_AGENT_PROMPT, - llm=model, - max_loops=1, - autosave=True, - dashboard=False, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="eth_agent.json", - user_name="eth_analyzer", - retry_attempts=1, - context_length=200000, - output_type="string", - streaming_on=False, - ) - - self.csv_filename = "ethereum_analysis.csv" - self.initialize_csv() - - def get_eth_price(self) -> float: - """Get current ETH price from CoinGecko API.""" - try: - response = requests.get( - "https://api.coingecko.com/api/v3/simple/price", - params={"ids": "ethereum", "vs_currencies": "usd"}, - ) - return float(response.json()["ethereum"]["usd"]) - except Exception as e: - logger.error(f"Error fetching ETH price: {str(e)}") - return 0.0 - - def update_eth_price(self): - """Update ETH price if more than 5 minutes have passed.""" - if time.time() - self.last_price_update > 300: # 5 minutes - self.eth_price = self.get_eth_price() - self.last_price_update = time.time() - logger.info(f"Updated ETH price: ${self.eth_price:,.2f}") - - def initialize_csv(self): - """Initialize CSV file with headers.""" - headers = [ - "timestamp", - "transaction_hash", - "from_address", - "to_address", - "value_eth", - "value_usd", - "eth_price", - "gas_used", - "gas_price_gwei", - "block_number", - "analysis", - ] - - if not os.path.exists(self.csv_filename): - with open(self.csv_filename, "w", newline="") as f: - writer = csv.writer(f) - writer.writerow(headers) - - async def analyze_transaction( - self, tx_hash: str - ) -> Optional[Dict[str, Any]]: - """Analyze a single transaction.""" - try: - tx = self.w3.eth.get_transaction(tx_hash) - receipt = self.w3.eth.get_transaction_receipt(tx_hash) - - value_eth = float(self.w3.from_wei(tx.value, "ether")) - - if value_eth < self.min_value_eth: - return None - - block = self.w3.eth.get_block(tx.blockNumber) - - # Update ETH price if needed - self.update_eth_price() - - value_usd = value_eth * self.eth_price - - analysis = { - "timestamp": datetime.fromtimestamp( - block.timestamp - ).isoformat(), - "transaction_hash": tx_hash.hex(), - "from_address": tx["from"], - "to_address": tx.to if tx.to else "Contract Creation", - "value_eth": value_eth, - "value_usd": value_usd, - "eth_price": self.eth_price, - "gas_used": receipt.gasUsed, - "gas_price_gwei": float( - self.w3.from_wei(tx.gasPrice, "gwei") - ), - "block_number": tx.blockNumber, - } - - # Check if it's a contract - if tx.to: - code = self.w3.eth.get_code(tx.to) - analysis["is_contract"] = len(code) > 0 - - # Get contract events - if analysis["is_contract"]: - analysis["events"] = receipt.logs - - return analysis - - except Exception as e: - logger.error( - f"Error analyzing transaction {tx_hash}: {str(e)}" - ) - return None - - 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"] - - prompt = f"""Analyze this Ethereum transaction in current market context: - -Transaction Details: -- Value: {tx_data['value_eth']:.2f} ETH (${value_usd:,.2f} at current price) -- Current ETH Price: ${eth_price:,.2f} -- From: {tx_data['from_address']} -- To: {tx_data['to_address']} -- Contract Interaction: {tx_data.get('is_contract', False)} -- Gas Used: {tx_data['gas_used']:,} units -- Gas Price: {tx_data['gas_price_gwei']:.2f} Gwei -- Block: {tx_data['block_number']} -- Timestamp: {tx_data['timestamp']} - -{f"Event Count: {len(tx_data['events'])} events" if tx_data.get('events') else "No contract events"} - -Consider the transaction's significance given the current ETH price of ${eth_price:,.2f} and total USD value of ${value_usd:,.2f}. -Analyze market impact, patterns, risks, and strategic implications.""" - - return prompt - - def save_to_csv(self, tx_data: Dict[str, Any], ai_analysis: str): - """Save transaction data and analysis to CSV.""" - row = [ - tx_data["timestamp"], - tx_data["transaction_hash"], - tx_data["from_address"], - tx_data["to_address"], - tx_data["value_eth"], - tx_data["value_usd"], - tx_data["eth_price"], - tx_data["gas_used"], - tx_data["gas_price_gwei"], - tx_data["block_number"], - ai_analysis.replace("\n", " "), - ] - - with open(self.csv_filename, "a", newline="") as f: - writer = csv.writer(f) - writer.writerow(row) - - async def monitor_transactions(self): - """Monitor and analyze transactions one at a time.""" - logger.info( - f"Starting transaction monitor (minimum value: {self.min_value_eth} ETH)" - ) - - while True: - try: - current_block = self.w3.eth.block_number - block = self.w3.eth.get_block( - current_block, full_transactions=True - ) - - for tx in block.transactions: - tx_analysis = await self.analyze_transaction( - tx.hash - ) - - if tx_analysis: - # Get AI analysis - analysis_prompt = ( - self.prepare_analysis_prompt(tx_analysis) - ) - ai_analysis = self.agent.run(analysis_prompt) - print(ai_analysis) - - # Save to CSV - self.save_to_csv(tx_analysis, ai_analysis) - - # Print analysis - print("\n" + "=" * 50) - print("New Transaction Analysis") - print( - f"Hash: {tx_analysis['transaction_hash']}" - ) - print( - f"Value: {tx_analysis['value_eth']:.2f} ETH (${tx_analysis['value_usd']:,.2f})" - ) - print( - f"Current ETH Price: ${self.eth_price:,.2f}" - ) - print("=" * 50) - print(ai_analysis) - print("=" * 50 + "\n") - - await asyncio.sleep(1) # Wait for next block - - except Exception as e: - logger.error(f"Error in monitoring loop: {str(e)}") - await asyncio.sleep(1) - - -async def main(): - """Entry point for the analysis system.""" - analyzer = EthereumAnalyzer(min_value_eth=100.0) - await analyzer.monitor_transactions() - - -if __name__ == "__main__": - print("Starting Ethereum Transaction Analyzer...") - print("Saving results to ethereum_analysis.csv") - print("Press Ctrl+C to stop") - try: - asyncio.run(main()) - except KeyboardInterrupt: - print("\nStopping analyzer...") diff --git a/new_features_examples/example_async_vs_multithread.py b/new_features_examples/example_async_vs_multithread.py deleted file mode 100644 index 25d514aa..00000000 --- a/new_features_examples/example_async_vs_multithread.py +++ /dev/null @@ -1,75 +0,0 @@ -import os -import asyncio -from swarms import Agent -from swarm_models import OpenAIChat -import time -import psutil - -from swarms.prompts.finance_agent_sys_prompt import ( - FINANCIAL_AGENT_SYS_PROMPT, -) -from dotenv import load_dotenv - -load_dotenv() - -# Get the OpenAI API key from the environment variable -api_key = os.getenv("OPENAI_API_KEY") - -# Create an instance of the OpenAIChat class -model = OpenAIChat( - openai_api_key=api_key, model_name="gpt-4o-mini", temperature=0.1 -) - -# Initialize the agent -agent = Agent( - agent_name="Financial-Analysis-Agent", - system_prompt=FINANCIAL_AGENT_SYS_PROMPT, - llm=model, - max_loops=1, - autosave=True, - dashboard=False, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="finance_agent.json", - user_name="swarms_corp", - retry_attempts=1, - context_length=200000, - return_step_meta=False, - output_type="string", - streaming_on=False, -) - - -# Function to measure time and memory usage -def measure_time_and_memory(func): - def wrapper(*args, **kwargs): - start_time = time.time() - result = func(*args, **kwargs) - end_time = time.time() - memory_usage = psutil.Process().memory_info().rss / 1024**2 - print(f"Time taken: {end_time - start_time} seconds") - print(f"Memory used: {memory_usage} MB") - return result - - return wrapper - - -# Function to run the agent asynchronously -@measure_time_and_memory -async def run_agent_async(): - await asyncio.gather( - agent.run( - "How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria" - ) - ) - - -# Function to run the agent on another thread -@measure_time_and_memory -def run_agent_thread(): - asyncio.run(run_agent_async()) - - -# Run the agent asynchronously and on another thread to test the speed -asyncio.run(run_agent_async()) -run_agent_thread() diff --git a/new_features_examples/forest_swarm_examples/fund_manager_forest.py b/new_features_examples/forest_swarm_examples/fund_manager_forest.py deleted file mode 100644 index afce82cf..00000000 --- a/new_features_examples/forest_swarm_examples/fund_manager_forest.py +++ /dev/null @@ -1,147 +0,0 @@ -from swarms.structs.tree_swarm import ForestSwarm, Tree, TreeAgent - -# Fund Analysis Tree -fund_agents = [ - TreeAgent( - system_prompt="""Mutual Fund Analysis Agent: - - Analyze mutual fund performance metrics and ratios - - Evaluate fund manager track records and strategy consistency - - Compare expense ratios and fee structures - - Assess fund holdings and sector allocations - - Monitor fund inflows/outflows and size implications - - Analyze risk-adjusted returns (Sharpe, Sortino ratios) - - Consider tax efficiency and distribution history - - Track style drift and benchmark adherence - Knowledge base: Mutual fund operations, portfolio management, fee structures - Output format: Fund analysis report with recommendations""", - agent_name="Mutual Fund Analyst", - ), - TreeAgent( - system_prompt="""Index Fund Specialist Agent: - - Evaluate index tracking accuracy and tracking error - - Compare different index methodologies - - Analyze index fund costs and tax efficiency - - Monitor index rebalancing impacts - - Assess market capitalization weightings - - Compare similar indices and their differences - - Evaluate smart beta and factor strategies - Knowledge base: Index construction, passive investing, market efficiency - Output format: Index fund comparison and selection recommendations""", - agent_name="Index Fund Specialist", - ), - TreeAgent( - system_prompt="""ETF Strategy Agent: - - Analyze ETF liquidity and trading volumes - - Evaluate creation/redemption mechanisms - - Compare ETF spreads and premium/discount patterns - - Assess underlying asset liquidity - - Monitor authorized participant activity - - Analyze securities lending revenue - - Compare similar ETFs and their structures - Knowledge base: ETF mechanics, trading strategies, market making - Output format: ETF analysis with trading recommendations""", - agent_name="ETF Strategist", - ), -] - -# Sector Specialist Tree -sector_agents = [ - TreeAgent( - system_prompt="""Energy Sector Analysis Agent: - - Track global energy market trends - - Analyze traditional and renewable energy companies - - Monitor regulatory changes and policy impacts - - Evaluate commodity price influences - - Assess geopolitical risk factors - - Track technological disruption in energy - - Analyze energy infrastructure investments - Knowledge base: Energy markets, commodities, regulatory environment - Output format: Energy sector analysis with investment opportunities""", - agent_name="Energy Sector Analyst", - ), - TreeAgent( - system_prompt="""AI and Technology Specialist Agent: - - Research AI company fundamentals and growth metrics - - Evaluate AI technology adoption trends - - Analyze AI chip manufacturers and supply chains - - Monitor AI software and service providers - - Track AI patent filings and R&D investments - - Assess competitive positioning in AI market - - Consider regulatory risks and ethical factors - Knowledge base: AI technology, semiconductor industry, tech sector dynamics - Output format: AI sector analysis with investment recommendations""", - agent_name="AI Technology Analyst", - ), - TreeAgent( - system_prompt="""Market Infrastructure Agent: - - Monitor trading platform stability - - Analyze market maker activity - - Track exchange system updates - - Evaluate clearing house operations - - Monitor settlement processes - - Assess cybersecurity measures - - Track regulatory compliance updates - Knowledge base: Market structure, trading systems, regulatory requirements - Output format: Market infrastructure assessment and risk analysis""", - agent_name="Infrastructure Monitor", - ), -] - -# Trading Strategy Tree -strategy_agents = [ - TreeAgent( - system_prompt="""Portfolio Strategy Agent: - - Develop asset allocation strategies - - Implement portfolio rebalancing rules - - Monitor portfolio risk metrics - - Optimize position sizing - - Calculate portfolio correlation matrices - - Implement tax-loss harvesting strategies - - Track portfolio performance attribution - Knowledge base: Portfolio theory, risk management, asset allocation - Output format: Portfolio strategy recommendations with implementation plan""", - agent_name="Portfolio Strategist", - ), - TreeAgent( - system_prompt="""Technical Analysis Agent: - - Analyze price patterns and trends - - Calculate technical indicators - - Identify support/resistance levels - - Monitor volume and momentum indicators - - Track market breadth metrics - - Analyze intermarket relationships - - Generate trading signals - Knowledge base: Technical analysis, chart patterns, market indicators - Output format: Technical analysis report with trade signals""", - agent_name="Technical Analyst", - ), - TreeAgent( - system_prompt="""Risk Management Agent: - - Calculate position-level risk metrics - - Monitor portfolio VaR and stress tests - - Track correlation changes - - Implement stop-loss strategies - - Monitor margin requirements - - Assess liquidity risk factors - - Generate risk alerts and warnings - Knowledge base: Risk metrics, position sizing, risk modeling - Output format: Risk assessment report with mitigation recommendations""", - agent_name="Risk Manager", - ), -] - -# Create trees -fund_tree = Tree(tree_name="Fund Analysis", agents=fund_agents) -sector_tree = Tree(tree_name="Sector Analysis", agents=sector_agents) -strategy_tree = Tree( - tree_name="Trading Strategy", agents=strategy_agents -) - -# Create the ForestSwarm -trading_forest = ForestSwarm( - trees=[fund_tree, sector_tree, strategy_tree] -) - -# Example usage -task = "Analyze current opportunities in AI sector ETFs considering market conditions and provide a risk-adjusted portfolio allocation strategy. Add in the names of the best AI etfs that are reliable and align with this strategy and also include where to purchase the etfs" -result = trading_forest.run(task) diff --git a/new_features_examples/forest_swarm_examples/medical_forest_swarm.py b/new_features_examples/forest_swarm_examples/medical_forest_swarm.py deleted file mode 100644 index 21e35acb..00000000 --- a/new_features_examples/forest_swarm_examples/medical_forest_swarm.py +++ /dev/null @@ -1,150 +0,0 @@ -from swarms.structs.tree_swarm import ForestSwarm, Tree, TreeAgent - -# Diagnostic Specialists Tree -diagnostic_agents = [ - TreeAgent( - system_prompt="""Primary Care Diagnostic Agent: - - Conduct initial patient assessment and triage - - Analyze patient symptoms, vital signs, and medical history - - Identify red flags and emergency conditions - - Coordinate with specialist agents for complex cases - - Provide preliminary diagnosis recommendations - - Consider common conditions and their presentations - - Factor in patient demographics and risk factors - Medical knowledge base: General medicine, common conditions, preventive care - Output format: Structured assessment with recommended next steps""", - agent_name="Primary Diagnostician", - ), - TreeAgent( - system_prompt="""Laboratory Analysis Agent: - - Interpret complex laboratory results - - Recommend appropriate test panels based on symptoms - - Analyze blood work, urinalysis, and other diagnostic tests - - Identify abnormal results and their clinical significance - - Suggest follow-up tests when needed - - Consider test accuracy and false positive/negative rates - - Integrate lab results with clinical presentation - Medical knowledge base: Clinical pathology, laboratory medicine, test interpretation - Output format: Detailed lab analysis with clinical correlations""", - agent_name="Lab Analyst", - ), - TreeAgent( - system_prompt="""Medical Imaging Specialist Agent: - - Analyze radiological images (X-rays, CT, MRI, ultrasound) - - Identify anatomical abnormalities and pathological changes - - Recommend appropriate imaging studies - - Correlate imaging findings with clinical symptoms - - Provide differential diagnoses based on imaging - - Consider radiation exposure and cost-effectiveness - - Suggest follow-up imaging when needed - Medical knowledge base: Radiology, anatomy, pathological imaging patterns - Output format: Structured imaging report with findings and recommendations""", - agent_name="Imaging Specialist", - ), -] - -# Treatment Specialists Tree -treatment_agents = [ - TreeAgent( - system_prompt="""Treatment Planning Agent: - - Develop comprehensive treatment plans based on diagnosis - - Consider evidence-based treatment guidelines - - Account for patient factors (age, comorbidities, preferences) - - Evaluate treatment risks and benefits - - Consider cost-effectiveness and accessibility - - Plan for treatment monitoring and adjustment - - Coordinate multi-modal treatment approaches - Medical knowledge base: Clinical guidelines, treatment protocols, medical management - Output format: Detailed treatment plan with rationale and monitoring strategy""", - agent_name="Treatment Planner", - ), - TreeAgent( - system_prompt="""Medication Management Agent: - - Recommend appropriate medications and dosing - - Check for drug interactions and contraindications - - Consider patient-specific factors affecting medication choice - - Provide medication administration guidelines - - Monitor for adverse effects and therapeutic response - - Suggest alternatives for contraindicated medications - - Plan medication tapering or adjustments - Medical knowledge base: Pharmacology, drug interactions, clinical pharmacotherapy - Output format: Medication plan with monitoring parameters""", - agent_name="Medication Manager", - ), - TreeAgent( - system_prompt="""Specialist Intervention Agent: - - Recommend specialized procedures and interventions - - Evaluate need for surgical vs. non-surgical approaches - - Consider procedural risks and benefits - - Provide pre- and post-procedure care guidelines - - Coordinate with other specialists - - Plan follow-up care and monitoring - - Handle complex cases requiring multiple interventions - Medical knowledge base: Surgical procedures, specialized interventions, perioperative care - Output format: Intervention plan with risk assessment and care protocol""", - agent_name="Intervention Specialist", - ), -] - -# Follow-up and Monitoring Tree -followup_agents = [ - TreeAgent( - system_prompt="""Recovery Monitoring Agent: - - Track patient progress and treatment response - - Identify complications or adverse effects early - - Adjust treatment plans based on response - - Coordinate follow-up appointments and tests - - Monitor vital signs and symptoms - - Evaluate treatment adherence and barriers - - Recommend lifestyle modifications - Medical knowledge base: Recovery patterns, complications, monitoring protocols - Output format: Progress report with recommendations""", - agent_name="Recovery Monitor", - ), - TreeAgent( - system_prompt="""Preventive Care Agent: - - Develop preventive care strategies - - Recommend appropriate screening tests - - Provide lifestyle and dietary guidance - - Monitor risk factors for disease progression - - Coordinate vaccination schedules - - Suggest health maintenance activities - - Plan long-term health monitoring - Medical knowledge base: Preventive medicine, health maintenance, risk reduction - Output format: Preventive care plan with timeline""", - agent_name="Prevention Specialist", - ), - TreeAgent( - system_prompt="""Patient Education Agent: - - Provide comprehensive patient education - - Explain conditions and treatments in accessible language - - Develop self-management strategies - - Create educational materials and resources - - Address common questions and concerns - - Provide lifestyle modification guidance - - Support treatment adherence - Medical knowledge base: Patient education, health literacy, behavior change - Output format: Educational plan with resources and materials""", - agent_name="Patient Educator", - ), -] - -# Create trees -diagnostic_tree = Tree( - tree_name="Diagnostic Specialists", agents=diagnostic_agents -) -treatment_tree = Tree( - tree_name="Treatment Specialists", agents=treatment_agents -) -followup_tree = Tree( - tree_name="Follow-up and Monitoring", agents=followup_agents -) - -# Create the ForestSwarm -medical_forest = ForestSwarm( - trees=[diagnostic_tree, treatment_tree, followup_tree] -) - -# Example usage -task = "Patient presents with persistent headache for 2 weeks, accompanied by visual disturbances and neck stiffness. Need comprehensive evaluation and treatment plan." -result = medical_forest.run(task) diff --git a/new_features_examples/forest_swarm_examples/tree_swarm_test.py b/new_features_examples/forest_swarm_examples/tree_swarm_test.py deleted file mode 100644 index cb0d41c7..00000000 --- a/new_features_examples/forest_swarm_examples/tree_swarm_test.py +++ /dev/null @@ -1,42 +0,0 @@ -from swarms.structs.tree_swarm import ForestSwarm, Tree, TreeAgent - - -agents_tree1 = [ - TreeAgent( - system_prompt="Stock Analysis Agent", - agent_name="Stock Analysis Agent", - ), - TreeAgent( - system_prompt="Financial Planning Agent", - agent_name="Financial Planning Agent", - ), - TreeAgent( - agent_name="Retirement Strategy Agent", - system_prompt="Retirement Strategy Agent", - ), -] - -agents_tree2 = [ - TreeAgent( - system_prompt="Tax Filing Agent", - agent_name="Tax Filing Agent", - ), - TreeAgent( - system_prompt="Investment Strategy Agent", - agent_name="Investment Strategy Agent", - ), - TreeAgent( - system_prompt="ROTH IRA Agent", agent_name="ROTH IRA Agent" - ), -] - -# Create trees -tree1 = Tree(tree_name="Financial Tree", agents=agents_tree1) -tree2 = Tree(tree_name="Investment Tree", agents=agents_tree2) - -# Create the ForestSwarm -multi_agent_structure = ForestSwarm(trees=[tree1, tree2]) - -# Run a task -task = "Our company is incorporated in delaware, how do we do our taxes for free?" -multi_agent_structure.run(task) diff --git a/new_features_examples/full_agent_rag_example.py b/new_features_examples/full_agent_rag_example.py deleted file mode 100644 index 75aee45b..00000000 --- a/new_features_examples/full_agent_rag_example.py +++ /dev/null @@ -1,228 +0,0 @@ -import os -from pathlib import Path -from typing import Optional - -from dotenv import load_dotenv -from llama_index.core import SimpleDirectoryReader, VectorStoreIndex -from loguru import logger -from swarm_models import OpenAIChat - -from swarms import Agent, AgentRearrange - -load_dotenv() - -# Get the OpenAI API key from the environment variable -api_key = os.getenv("GROQ_API_KEY") - -# Model -model = OpenAIChat( - openai_api_base="https://api.groq.com/openai/v1", - openai_api_key=api_key, - model_name="llama-3.1-70b-versatile", - temperature=0.1, -) - - -class LlamaIndexDB: - """A class to manage document indexing and querying using LlamaIndex. - - This class provides functionality to add documents from a directory and query the indexed documents. - - Args: - data_dir (str): Directory containing documents to index. Defaults to "docs". - **kwargs: Additional arguments passed to SimpleDirectoryReader and VectorStoreIndex. - SimpleDirectoryReader kwargs: - - filename_as_id (bool): Use filenames as document IDs - - recursive (bool): Recursively read subdirectories - - required_exts (List[str]): Only read files with these extensions - - exclude_hidden (bool): Skip hidden files - - VectorStoreIndex kwargs: - - service_context: Custom service context - - embed_model: Custom embedding model - - similarity_top_k (int): Number of similar docs to retrieve - - store_nodes_override (bool): Override node storage - """ - - def __init__(self, data_dir: str = "docs", **kwargs) -> None: - """Initialize the LlamaIndexDB with an empty index. - - Args: - data_dir (str): Directory containing documents to index - **kwargs: Additional arguments for SimpleDirectoryReader and VectorStoreIndex - """ - self.data_dir = data_dir - self.index: Optional[VectorStoreIndex] = None - self.reader_kwargs = { - k: v - for k, v in kwargs.items() - if k - in SimpleDirectoryReader.__init__.__code__.co_varnames - } - self.index_kwargs = { - k: v - for k, v in kwargs.items() - if k not in self.reader_kwargs - } - - logger.info("Initialized LlamaIndexDB") - data_path = Path(self.data_dir) - if not data_path.exists(): - logger.error(f"Directory not found: {self.data_dir}") - raise FileNotFoundError( - f"Directory {self.data_dir} does not exist" - ) - - try: - documents = SimpleDirectoryReader( - self.data_dir, **self.reader_kwargs - ).load_data() - self.index = VectorStoreIndex.from_documents( - documents, **self.index_kwargs - ) - logger.success( - f"Successfully indexed documents from {self.data_dir}" - ) - except Exception as e: - logger.error(f"Error indexing documents: {str(e)}") - raise - - def query(self, query: str, **kwargs) -> str: - """Query the indexed documents. - - Args: - query (str): The query string to search for - **kwargs: Additional arguments passed to the query engine - - similarity_top_k (int): Number of similar documents to retrieve - - streaming (bool): Enable streaming response - - response_mode (str): Response synthesis mode - - max_tokens (int): Maximum tokens in response - - Returns: - str: The response from the query engine - - Raises: - ValueError: If no documents have been indexed yet - """ - if self.index is None: - logger.error("No documents have been indexed yet") - raise ValueError("Must add documents before querying") - - try: - query_engine = self.index.as_query_engine(**kwargs) - response = query_engine.query(query) - print(response) - logger.info(f"Successfully queried: {query}") - return str(response) - except Exception as e: - logger.error(f"Error during query: {str(e)}") - raise - - -# Initialize specialized medical agents -medical_data_extractor = Agent( - agent_name="Medical-Data-Extractor", - system_prompt="You are a specialized medical data extraction expert, trained in processing and analyzing clinical data, lab results, medical imaging reports, and patient records. Your role is to carefully extract relevant medical information while maintaining strict HIPAA compliance and patient confidentiality. Focus on identifying key clinical indicators, test results, vital signs, medication histories, and relevant patient history. Pay special attention to temporal relationships between symptoms, treatments, and outcomes. Ensure all extracted data maintains proper medical context and terminology.", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="medical_data_extractor.json", - user_name="medical_team", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -diagnostic_specialist = Agent( - agent_name="Diagnostic-Specialist", - system_prompt="You are a senior diagnostic physician with extensive experience in differential diagnosis. Your role is to analyze patient symptoms, lab results, and clinical findings to develop comprehensive diagnostic assessments. Consider all presenting symptoms, patient history, risk factors, and test results to formulate possible diagnoses. Prioritize diagnoses based on clinical probability and severity. Always consider both common and rare conditions that match the symptom pattern. Recommend additional tests or imaging when needed for diagnostic clarity. Follow evidence-based diagnostic criteria and current medical guidelines.", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="diagnostic_specialist.json", - user_name="medical_team", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -treatment_planner = Agent( - agent_name="Treatment-Planner", - system_prompt="You are an experienced clinical treatment specialist focused on developing comprehensive treatment plans. Your expertise covers both acute and chronic condition management, medication selection, and therapeutic interventions. Consider patient-specific factors including age, comorbidities, allergies, and contraindications when recommending treatments. Incorporate both pharmacological and non-pharmacological interventions. Emphasize evidence-based treatment protocols while considering patient preferences and quality of life. Address potential drug interactions and side effects. Include monitoring parameters and treatment milestones.", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="treatment_planner.json", - user_name="medical_team", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -specialist_consultant = Agent( - agent_name="Specialist-Consultant", - system_prompt="You are a medical specialist consultant with expertise across multiple disciplines including cardiology, neurology, endocrinology, and internal medicine. Your role is to provide specialized insight for complex cases requiring deep domain knowledge. Analyze cases from your specialist perspective, considering rare conditions and complex interactions between multiple systems. Provide detailed recommendations for specialized testing, imaging, or interventions within your domain. Highlight potential complications or considerations that may not be immediately apparent to general practitioners.", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="specialist_consultant.json", - user_name="medical_team", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -patient_care_coordinator = Agent( - agent_name="Patient-Care-Coordinator", - system_prompt="You are a patient care coordinator specializing in comprehensive healthcare management. Your role is to ensure holistic patient care by coordinating between different medical specialists, considering patient needs, and managing care transitions. Focus on patient education, medication adherence, lifestyle modifications, and follow-up care planning. Consider social determinants of health, patient resources, and access to care. Develop actionable care plans that patients can realistically follow. Coordinate with other healthcare providers to ensure continuity of care and proper implementation of treatment plans.", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="patient_care_coordinator.json", - user_name="medical_team", - retry_attempts=1, - context_length=200000, - output_type="string", -) - - -# Initialize the SwarmRouter to coordinate the medical agents -router = AgentRearrange( - name="medical-diagnosis-treatment-swarm", - description="Collaborative medical team for comprehensive patient diagnosis and treatment planning", - max_loops=1, # Limit to one iteration through the agent flow - agents=[ - medical_data_extractor, # First agent to extract medical data - diagnostic_specialist, # Second agent to analyze and diagnose - treatment_planner, # Third agent to plan treatment - specialist_consultant, # Fourth agent to provide specialist input - patient_care_coordinator, # Final agent to coordinate care plan - ], - # Configure the document storage and retrieval system - memory_system=LlamaIndexDB( - data_dir="docs", # Directory containing medical documents - filename_as_id=True, # Use filenames as document identifiers - recursive=True, # Search subdirectories - # required_exts=[".txt", ".pdf", ".docx"], # Supported file types - similarity_top_k=10, # Return top 10 most relevant documents - ), - # Define the sequential flow of information between agents - flow=f"{medical_data_extractor.agent_name} -> {diagnostic_specialist.agent_name} -> {treatment_planner.agent_name} -> {specialist_consultant.agent_name} -> {patient_care_coordinator.agent_name}", -) - -# Example usage -if __name__ == "__main__": - # Run a comprehensive medical analysis task for patient Lucas Brown - router.run( - "Analyze this Lucas Brown's medical data to provide a diagnosis and treatment plan" - ) diff --git a/new_features_examples/gemini_model.py b/new_features_examples/gemini_model.py deleted file mode 100644 index f38fa1da..00000000 --- a/new_features_examples/gemini_model.py +++ /dev/null @@ -1,63 +0,0 @@ -import os -import google.generativeai as genai -from loguru import logger - - -class GeminiModel: - """ - Represents a GeminiModel instance for generating text based on user input. - """ - - def __init__( - self, - temperature: float, - top_p: float, - top_k: float, - ): - """ - Initializes the GeminiModel by setting up the API key, generation configuration, and starting a chat session. - Raises a KeyError if the GEMINI_API_KEY environment variable is not found. - """ - try: - api_key = os.environ["GEMINI_API_KEY"] - genai.configure(api_key=api_key) - self.generation_config = { - "temperature": 1, - "top_p": 0.95, - "top_k": 40, - "max_output_tokens": 8192, - "response_mime_type": "text/plain", - } - self.model = genai.GenerativeModel( - model_name="gemini-1.5-pro", - generation_config=self.generation_config, - ) - self.chat_session = self.model.start_chat(history=[]) - except KeyError as e: - logger.error(f"Environment variable not found: {e}") - raise - - def run(self, task: str) -> str: - """ - Sends a message to the chat session and returns the response text. - Raises an Exception if there's an error running the GeminiModel. - - Args: - task (str): The input task or message to send to the chat session. - - Returns: - str: The response text from the chat session. - """ - try: - response = self.chat_session.send_message(task) - return response.text - except Exception as e: - logger.error(f"Error running GeminiModel: {e}") - raise - - -# Example usage -if __name__ == "__main__": - gemini_model = GeminiModel() - output = gemini_model.run("INSERT_INPUT_HERE") - print(output) diff --git a/new_features_examples/health_privacy_swarm.py b/new_features_examples/health_privacy_swarm.py deleted file mode 100644 index 2125f678..00000000 --- a/new_features_examples/health_privacy_swarm.py +++ /dev/null @@ -1,265 +0,0 @@ -import os -from swarms import Agent, AgentRearrange -from swarm_models import OpenAIChat - -# Get the OpenAI API key from the environment variable -api_key = os.getenv("OPENAI_API_KEY") - -# Create an instance of the OpenAIChat class -model = OpenAIChat( - api_key=api_key, model_name="gpt-4o-mini", temperature=0.1 -) - -# Initialize the gatekeeper agent -gatekeeper_agent = Agent( - agent_name="HealthScoreGatekeeper", - system_prompt=""" - - Health Score Privacy Gatekeeper - Protect and manage sensitive health information while providing necessary access to authorized agents - - - - - Manage encryption of health scores - Implement strict access control mechanisms - Track and log all access requests - - - Remove personally identifiable information - Convert raw health data into privacy-preserving formats - - - - - - - Verify agent authorization level - Check request legitimacy - Validate purpose of access - - - Numerical value only - Anonymized timestamp and request ID - - - - Never expose patient names or identifiers - No access to historical data without explicit authorization - Provide only aggregated or anonymized data when possible - - - - - - Maintain HIPAA compliance - Follow GDPR guidelines for data protection - - - Record all data access events - Track unusual access patterns - - - """, - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="gatekeeper_agent.json", -) - -# Initialize the boss agent (Director) -boss_agent = Agent( - agent_name="BossAgent", - system_prompt=""" - - Swarm Director - Orchestrate and manage agent collaboration while respecting privacy boundaries - - - - - Assign and prioritize tasks - Ensure efficient collaboration - Maintain privacy protocols - - - Track agent effectiveness - Ensure accuracy of outputs - Enforce data protection policies - - - - - - Request access through gatekeeper only - Process only anonymized health scores - Share authorized information on need-to-know basis - - - Structured, secure messaging - End-to-end encrypted channels - - - """, - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="boss_agent.json", -) - -# Initialize worker 1: Health Score Analyzer -worker1 = Agent( - agent_name="HealthScoreAnalyzer", - system_prompt=""" - - Health Score Analyst - Analyze anonymized health scores for patterns and insights - - - - - Advanced statistical analysis - Identify health trends - Evaluate health risk factors - - - Work only with anonymized data - Use encrypted analysis methods - - - - - - - Submit authenticated requests to gatekeeper - Process only authorized data - Maintain audit trail - - - - Ensure no identifiable information in reports - Present aggregate statistics only - - - """, - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="worker1.json", -) - -# Initialize worker 2: Report Generator -worker2 = Agent( - agent_name="ReportGenerator", - system_prompt=""" - - Privacy-Conscious Report Generator - Create secure, anonymized health score reports - - - - - Generate standardized, secure reports - Apply privacy-preserving techniques - Compile statistical summaries - - - Implement secure report generation - Manage report distribution - - - - - - - No personal identifiers in reports - Aggregate data when possible - Apply statistical noise for privacy - - - Restricted to authorized personnel - Monitor report access - - - - """, - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="worker2.json", -) - -# Swarm-Level Prompt (Collaboration Prompt) -swarm_prompt = """ - - Process and analyze health scores while maintaining strict privacy controls - - - HealthScoreGatekeeper - Receive and validate data access requests - Anonymized health scores - - - BossAgent - Coordinate analysis and reporting tasks - Enforce data protection protocols - - - HealthScoreAnalyzer - Process authorized health score data - Work only with anonymized information - - - ReportGenerator - Create privacy-preserving reports - Secure, anonymized insights - - - -""" - -# Create a list of agents -agents = [gatekeeper_agent, boss_agent, worker1, worker2] - -# Define the flow pattern for the swarm -flow = "HealthScoreGatekeeper -> BossAgent -> HealthScoreAnalyzer -> ReportGenerator" - -# Using AgentRearrange class to manage the swarm -agent_system = AgentRearrange( - name="health-score-swarm", - description="Privacy-focused health score analysis system", - agents=agents, - flow=flow, - return_json=False, - output_type="final", - max_loops=1, -) - -# 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 - without exposing any personally identifiable information. -""" - -# Run the swarm system with the task -output = agent_system.run(task) -print(output) diff --git a/new_features_examples/health_privacy_swarm_two.py b/new_features_examples/health_privacy_swarm_two.py deleted file mode 100644 index 674581c8..00000000 --- a/new_features_examples/health_privacy_swarm_two.py +++ /dev/null @@ -1,291 +0,0 @@ -import os -from swarms import Agent, AgentRearrange -from swarm_models import OpenAIChat - -# Initialize OpenAI model -api_key = os.getenv( - "OPENAI_API_KEY" -) # ANTHROPIC_API_KEY, COHERE_API_KEY -model = OpenAIChat( - api_key=api_key, - model_name="gpt-4o-mini", - temperature=0.7, # Higher temperature for more creative responses -) - -# Patient Agent - Holds and protects private information -patient_agent = Agent( - agent_name="PatientAgent", - system_prompt=""" - - Anxious Patient with Private Health Information - - - Protective of personal information - Slightly distrustful of medical system - Worried about health insurance rates - Selective in information sharing - - - Previous negative experience with information leaks - Fear of discrimination based on health status - - - - - - - Maintains actual health score - Knowledge of undisclosed conditions - Complete list of current medications - Full medical history - - - - Only share general symptoms with doctor - Withhold specific details about lifestyle - Never reveal full medication list - Protect actual health score value - - - - - - - - Deflect sensitive questions - Provide partial information when pressed - Become evasive if pressured too much - - - Share only what's absolutely necessary - Redirect personal questions - - - - """, - llm=model, - max_loops=1, - verbose=True, - stopping_token="", -) - -# Doctor Agent - Tries to gather accurate information -doctor_agent = Agent( - agent_name="DoctorAgent", - system_prompt=""" - - Empathetic but Thorough Medical Professional - - - Patient and understanding - Professionally persistent - Detail-oriented - Trust-building focused - - - - Uses indirect questions to gather information - - - - - - - - Ask open-ended questions - Notice inconsistencies in responses - Build rapport before sensitive questions - Use medical knowledge to probe deeper - - - - - Explain importance of full disclosure - Provide privacy assurances - Use empathetic listening - - - - - - - - Establish trust and rapport - Gather general health information - Carefully probe sensitive areas - Respect patient boundaries while encouraging openness - - - - """, - llm=model, - max_loops=1, - verbose=True, - stopping_token="", -) - -# Nurse Agent - Observes and assists -nurse_agent = Agent( - agent_name="NurseAgent", - system_prompt=""" - - Observant Support Medical Staff - - - Highly perceptive - Naturally trustworthy - Diplomatically skilled - - - Support doctor-patient communication - Notice non-verbal cues - - - - - - - - Patient body language - Inconsistencies in stories - Signs of withholding information - Emotional responses to questions - - - - - Provide comfortable environment - Offer reassurance when needed - Bridge communication gaps - - - - - - - - Share observations with doctor privately - Help patient feel more comfortable - Facilitate trust-building - - - - """, - llm=model, - max_loops=1, - verbose=True, - stopping_token="", -) - -# Medical Records Agent - Analyzes available information -records_agent = Agent( - agent_name="MedicalRecordsAgent", - system_prompt=""" - - Medical Records Analyst - - Analyze available medical information - Identify patterns and inconsistencies - - - - - - - Compare current and historical data - Identify information gaps - Flag potential inconsistencies - Generate questions for follow-up - - - - - Summarize known information - List missing critical data - Suggest areas for investigation - - - - - - - - Work only with authorized information - Maintain strict confidentiality - Flag but don't speculate about gaps - - - - """, - llm=model, - max_loops=1, - verbose=True, - stopping_token="", -) - -# Swarm-Level Prompt (Medical Consultation Scenario) -swarm_prompt = """ - - - Private medical office - Routine health assessment with complex patient - - - - - PatientAgent - Present for check-up, holding private information - - - - DoctorAgent - Conduct examination and gather information - NurseAgent - Observe and support interaction - - - - MedicalRecordsAgent - Process available information and identify gaps - - - - - Create realistic medical consultation interaction - Demonstrate information protection dynamics - Show natural healthcare provider-patient relationship - - -""" - -# Create agent list -agents = [patient_agent, doctor_agent, nurse_agent, records_agent] - -# Define interaction flow -flow = ( - "PatientAgent -> DoctorAgent -> NurseAgent -> MedicalRecordsAgent" -) - -# Configure swarm system -agent_system = AgentRearrange( - name="medical-consultation-swarm", - description="Role-playing medical consultation with focus on information privacy", - agents=agents, - flow=flow, - return_json=False, - output_type="final", - max_loops=1, -) - -# 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 - observes the interaction. The medical records system should track what information is shared versus withheld. -""" - -# Run the consultation scenario -output = agent_system.run(task) -print(output) diff --git a/new_features_examples/insurance_agent.py b/new_features_examples/insurance_agent.py deleted file mode 100644 index a4c5d27b..00000000 --- a/new_features_examples/insurance_agent.py +++ /dev/null @@ -1,169 +0,0 @@ -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: -You are a Claims Processing Agent specializing in automating and accelerating claims processing workflows. Your primary goal is to ensure Accuracy, reduce processing time, and flag potential fraud while providing clear and actionable insights. You must follow the detailed steps below to process claims efficiently and provide consistent, structured output. - -### Primary Objectives: -1. **Extract Information**: - - Identify and extract key details from claim documents such as: - - Claimant name, date of incident, and location. - - Relevant policy numbers and coverage details. - - Information from supporting documents like police reports, medical bills, or repair estimates. - - For images (e.g., accident photos), extract descriptive metadata and identify key features (e.g., vehicle damage, environmental factors). - -2. **Cross-Reference**: - - Compare details across documents and media: - - Validate consistency between police reports, medical bills, and other supporting documents. - - Cross-check dates, times, and locations for coherence. - - Analyze image evidence and correlate it with textual claims for verification. - -3. **Fraud Detection**: - - Apply analytical reasoning to identify inconsistencies or suspicious patterns, such as: - - Discrepancies in timelines, damages, or descriptions. - - Repetitive or unusually frequent claims involving the same parties or locations. - - Signs of manipulated or altered evidence. - -4. **Provide a Risk Assessment**: - - Assign a preliminary risk level to the claim based on your analysis (e.g., Low, Medium, High). - - Justify the risk level with a clear explanation. - -5. **Flag and Recommend**: - - Highlight any flagged concerns for human review and provide actionable recommendations. - - Indicate documents, areas, or sections requiring further investigation. - ---- - -### Reasoning Steps: -Follow these steps to ensure comprehensive and accurate claim processing: -1. **Document Analysis**: - - Analyze each document individually to extract critical details. - - Identify any missing or incomplete information. -2. **Data Cross-Referencing**: - - Check for consistency between documents. - - Use contextual reasoning to spot potential discrepancies. -3. **Fraud Pattern Analysis**: - - Apply pattern recognition to flag anomalies or unusual claims. -4. **Risk Assessment**: - - Summarize your findings and categorize the risk. -5. **Final Recommendations**: - - Provide clear next steps for resolution or escalation. - ---- - -### Output Format: -Your output must be structured as follows: - -#### 1. Extracted Information: -``` -Claimant Name: [Name] -Date of Incident: [Date] -Location: [Location] -Policy Number: [Policy Number] -Summary of Incident: [Brief Summary] -Supporting Documents: - - Police Report: [Key Details] - - Medical Bills: [Key Details] - - Repair Estimate: [Key Details] - - Photos: [Key Observations] -``` - -#### 2. Consistency Analysis: -``` -[Provide a detailed comparison of documents, highlighting any inconsistencies or gaps in data.] -``` - -#### 3. Risk Assessment: -``` -Risk Level: [Low / Medium / High] -Reasoning: [Provide justification for the assigned risk level, supported by evidence from the analysis.] -``` - -#### 4. Flagged Concerns and Recommendations: -``` -Flagged Concerns: -- [Detail specific issues or inconsistencies, e.g., timeline mismatch, suspicious patterns, etc.] - -Recommendations: -- [Provide actionable next steps for resolving the claim or escalating for human review.] -``` - ---- - -### Example Task: -**Input**: -"Process the attached car accident claim. Extract details from the police report, analyze the attached images, and provide an initial risk assessment. Highlight any inconsistencies for human review." - -**Output**: -#### 1. Extracted Information: -``` -Claimant Name: John Doe -Date of Incident: 2024-01-15 -Location: Miami, FL -Policy Number: ABC-12345 -Summary of Incident: The claimant reports being rear-ended at a traffic light. - -Supporting Documents: - - Police Report: Incident verified by Officer Jane Smith; driver's statement matches claimant's report. - - Medical Bills: $1,500 for physical therapy; injury type aligns with collision severity. - - Repair Estimate: $4,000 for rear bumper and trunk damage. - - Photos: Damage visible to rear bumper; no damage visible to other vehicle. -``` - -#### 2. Consistency Analysis: -``` -- Police Report and Claimant Statement: Consistent. -- Medical Bills and Injury Details: Consistent with collision type. -- Repair Estimate and Photos: Consistent; no indications of additional hidden damage. -- No discrepancies in timeline or location details. -``` - -#### 3. Risk Assessment: -``` -Risk Level: Low -Reasoning: All supporting documents align with the claimant's statement, and no unusual patterns or inconsistencies were identified. -``` - -#### 4. Flagged Concerns and Recommendations: -``` -Flagged Concerns: -- None identified. - -Recommendations: -- Proceed with claim approval and settlement. -``` - ---- - -### Additional Notes: -- Always ensure outputs are clear, professional, and comprehensive. -- Use concise, evidence-backed reasoning to justify all conclusions. -- Where relevant, prioritize human review for flagged concerns or high-risk cases. -""" - -# Initialize the Claims Processing Agent with RAG capabilities -agent = Agent( - agent_name="Claims-Processing-Agent", - system_prompt=CLAIMS_PROCESSING_AGENT_SYS_PROMPT, - agent_description="Agent automates claims processing and fraud detection.", - model_name="gpt-4o-mini", - max_loops="auto", # Auto-adjusts loops based on task complexity - autosave=True, # Automatically saves agent state - dashboard=False, # Disables dashboard for this example - verbose=True, # Enables verbose mode for detailed output - streaming_on=True, # Enables streaming for real-time processing - dynamic_temperature_enabled=True, # Dynamically adjusts temperature for optimal performance - saved_state_path="claims_processing_agent.json", # Path to save agent state - user_name="swarms_corp", # User name for the agent - retry_attempts=3, # Number of retry attempts for failed tasks - context_length=200000, # Maximum length of the context to consider - return_step_meta=False, - output_type="string", -) - -# Sample task for the Claims Processing Agent -agent.run( - "Process the attached car accident claim. Extract details from the police report, analyze the attached images, and provide an initial risk assessment. Highlight any inconsistencies for human review." -) diff --git a/new_features_examples/insurance_swarm.py b/new_features_examples/insurance_swarm.py deleted file mode 100644 index 1f58902b..00000000 --- a/new_features_examples/insurance_swarm.py +++ /dev/null @@ -1,327 +0,0 @@ -import asyncio -from dataclasses import dataclass -from enum import Enum -from typing import List, Optional - -from swarms import Agent - - -class InsuranceType(Enum): - AUTO = "auto" - LIFE = "life" - HEALTH = "health" - HOME = "home" - BUSINESS = "business" - DENTAL = "dental" - TRAVEL = "travel" - - -@dataclass -class InsuranceProduct: - code: str - name: str - type: InsuranceType - description: str - coverage: List[str] - price_range: str - min_coverage: float - max_coverage: float - payment_options: List[str] - waiting_period: str - available: bool - - -# Simulated product database -INSURANCE_PRODUCTS = { - "AUTO001": InsuranceProduct( - code="AUTO001", - name="Seguro Auto Total", - type=InsuranceType.AUTO, - description="Seguro completo para vehículos con cobertura integral", - coverage=[ - "Daños por colisión", - "Robo total", - "Responsabilidad civil", - "Asistencia en carretera 24/7", - "Gastos médicos ocupantes", - ], - price_range="$800-2000 USD/año", - min_coverage=10000, - max_coverage=50000, - payment_options=["Mensual", "Trimestral", "Anual"], - waiting_period="Inmediata", - available=True, - ), - "LIFE001": InsuranceProduct( - code="LIFE001", - name="Vida Protegida Plus", - type=InsuranceType.LIFE, - description="Seguro de vida con cobertura extendida y beneficios adicionales", - coverage=[ - "Muerte natural", - "Muerte accidental (doble indemnización)", - "Invalidez total y permanente", - "Enfermedades graves", - "Gastos funerarios", - ], - price_range="$30-100 USD/mes", - min_coverage=50000, - max_coverage=1000000, - payment_options=["Mensual", "Anual"], - waiting_period="30 días", - available=True, - ), - "HEALTH001": InsuranceProduct( - code="HEALTH001", - name="Salud Preferencial", - type=InsuranceType.HEALTH, - description="Plan de salud premium con cobertura internacional", - coverage=[ - "Hospitalización", - "Cirugías", - "Consultas médicas", - "Medicamentos", - "Tratamientos especializados", - "Cobertura internacional", - ], - price_range="$100-300 USD/mes", - min_coverage=100000, - max_coverage=5000000, - payment_options=["Mensual", "Anual"], - waiting_period="90 días", - available=True, - ), -} - - -class WorkflowNode(Enum): - MAIN_MENU = "main_menu" - CHECK_AVAILABILITY = "check_availability" - PRODUCT_DETAILS = "product_details" - QUOTE_REQUEST = "quote_request" - CLAIMS = "claims" - LOCATE_OFFICE = "locate_office" - PAYMENT_OPTIONS = "payment_options" - - -LATAM_LOCATIONS = { - "Brasil": [ - { - "city": "São Paulo", - "offices": [ - { - "address": "Av. Paulista, 1374 - Bela Vista", - "phone": "+55 11 1234-5678", - "hours": "Lun-Vie: 9:00-18:00", - } - ], - } - ], - "México": [ - { - "city": "Ciudad de México", - "offices": [ - { - "address": "Paseo de la Reforma 250, Juárez", - "phone": "+52 55 1234-5678", - "hours": "Lun-Vie: 9:00-18:00", - } - ], - } - ], -} - - -class InsuranceBot: - def __init__(self): - 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 - - Provide detailed coverage information - - Compare plans and benefits - - Quote estimates based on customer needs - -2. Customer Service: - - Process policy inquiries - - Handle claims information - - Assist with payment options - - Locate nearest offices - -3. Cultural Considerations: - - Communicate in Spanish and Portuguese - - Understand LATAM insurance regulations - - Consider regional healthcare systems - - Respect local customs and practices - -Use the following simulated product database for accurate information: -{INSURANCE_PRODUCTS} - -When discussing products, always reference accurate prices, coverage amounts, and waiting periods.""", - model_name="gpt-4", - max_loops=1, - verbose=True, - ) - - self.current_node = WorkflowNode.MAIN_MENU - self.current_product = None - - async def process_user_input(self, user_input: str) -> str: - """Process user input and return appropriate response""" - try: - if self.current_node == WorkflowNode.MAIN_MENU: - menu_choice = user_input.strip() - - if menu_choice == "1": - # 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 -- HEALTH001: Salud Preferencial - -Explique brevemente cada uno y solicite información sobre sus necesidades específicas.""" - ) - - elif menu_choice == "2": - self.current_node = WorkflowNode.QUOTE_REQUEST - # Use agent to handle quote requests - return await self.agent.run( - """Inicie el proceso de cotización. - Solicite la siguiente información de manera conversacional: - 1. Tipo de seguro - 2. Información personal básica - 3. Necesidades específicas de cobertura""" - ) - - elif menu_choice == "3": - return await self.agent.run( - """Explique el proceso de reclamos para cada tipo de seguro, - incluyendo documentación necesaria y tiempos estimados.""" - ) - - elif menu_choice == "4": - self.current_node = WorkflowNode.LOCATE_OFFICE - # Use agent to provide location guidance - return await self.agent.run( - f"""Based on our office locations: {LATAM_LOCATIONS} - Ask the customer for their location and help them find the nearest office. - Provide the response in Spanish.""" - ) - - elif menu_choice == "5": - # Use agent to explain payment options - return await self.agent.run( - """Explique todas las opciones de pago disponibles, - incluyendo métodos, frecuencias y cualquier descuento por pago anticipado.""" - ) - - elif menu_choice == "6": - # Use agent to handle advisor connection - return await self.agent.run( - """Explique el proceso para conectar con un asesor personal, - horarios de atención y canales disponibles.""" - ) - - else: - return await self.agent.run( - "Explain that the option is invalid and list the main menu options." - ) - - elif self.current_node == WorkflowNode.LOCATE_OFFICE: - # Use agent to process location request - return await self.agent.run( - f"""Based on user input: '{user_input}' - and our office locations: {LATAM_LOCATIONS} - Help them find the most relevant office. Response in Spanish.""" - ) - - # Check if input is a product code - if user_input.upper() in INSURANCE_PRODUCTS: - product = self.get_product_info(user_input.upper()) - # Use agent to provide detailed product information - return await self.agent.run( - f"""Provide detailed information about this product: - {self.format_product_info(product)} - Include additional benefits and comparison with similar products. - Response in Spanish.""" - ) - - # Handle general queries - return await self.agent.run( - f"""The user said: '{user_input}' - Provide a helpful response based on our insurance products and services. - Response in Spanish.""" - ) - - except Exception: - self.current_node = WorkflowNode.MAIN_MENU - return await self.agent.run( - "Explain that there was an error and list the main menu options. Response in Spanish." - ) - - def get_product_info( - self, product_code: str - ) -> Optional[InsuranceProduct]: - """Get product information from simulated database""" - return INSURANCE_PRODUCTS.get(product_code) - - def format_product_info(self, product: InsuranceProduct) -> str: - """Format product information for display""" - return f""" - Producto: {product.name} (Código: {product.code}) - Tipo: {product.type.value} - Descripción: {product.description} - - Cobertura incluye: - {chr(10).join(f'- {coverage}' for coverage in product.coverage)} - - Rango de precio: {product.price_range} - Cobertura mínima: ${product.min_coverage:,.2f} USD - Cobertura máxima: ${product.max_coverage:,.2f} USD - - Opciones de pago: {', '.join(product.payment_options)} - Período de espera: {product.waiting_period} - Estado: {'Disponible' if product.available else 'No disponible'} - """ - - def handle_main_menu(self) -> List[str]: - """Return main menu options""" - return [ - "1. Consultar productos de seguro", - "2. Solicitar cotización", - "3. Información sobre reclamos", - "4. Ubicar oficina más cercana", - "5. Opciones de pago", - "6. Hablar con un asesor", - ] - - -async def main(): - """Run the interactive session""" - bot = InsuranceBot() - - print( - "Sistema de Seguros LATAM inicializado. Escriba 'salir' para terminar." - ) - print("\nOpciones disponibles:") - print("\n".join(bot.handle_main_menu())) - - while True: - user_input = input("\nUsted: ").strip() - - if user_input.lower() in ["salir", "exit"]: - print("¡Gracias por usar nuestro servicio!") - break - - response = await bot.process_user_input(user_input) - print(f"Agente: {response}") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/new_features_examples/main.py b/new_features_examples/main.py deleted file mode 100644 index 9cd2db5c..00000000 --- a/new_features_examples/main.py +++ /dev/null @@ -1,272 +0,0 @@ -from typing import List, Dict -from dataclasses import dataclass -from datetime import datetime -import asyncio -import aiohttp -from loguru import logger -from swarms import Agent -from pathlib import Path -import json - - -@dataclass -class CryptoData: - """Real-time cryptocurrency data structure""" - - symbol: str - current_price: float - market_cap: float - total_volume: float - price_change_24h: float - market_cap_rank: int - - -class DataFetcher: - """Handles real-time data fetching from CoinGecko""" - - def __init__(self): - self.base_url = "https://api.coingecko.com/api/v3" - self.session = None - - async def _init_session(self): - if self.session is None: - self.session = aiohttp.ClientSession() - - async def close(self): - if self.session: - await self.session.close() - self.session = None - - async def get_market_data( - self, limit: int = 20 - ) -> List[CryptoData]: - """Fetch market data for top cryptocurrencies""" - await self._init_session() - - url = f"{self.base_url}/coins/markets" - params = { - "vs_currency": "usd", - "order": "market_cap_desc", - "per_page": str(limit), - "page": "1", - "sparkline": "false", - } - - try: - async with self.session.get( - url, params=params - ) as response: - if response.status != 200: - logger.error( - f"API Error {response.status}: {await response.text()}" - ) - return [] - - data = await response.json() - crypto_data = [] - - for coin in data: - try: - crypto_data.append( - CryptoData( - symbol=str( - coin.get("symbol", "") - ).upper(), - current_price=float( - coin.get("current_price", 0) - ), - market_cap=float( - coin.get("market_cap", 0) - ), - total_volume=float( - coin.get("total_volume", 0) - ), - price_change_24h=float( - coin.get("price_change_24h", 0) - ), - market_cap_rank=int( - coin.get("market_cap_rank", 0) - ), - ) - ) - except (ValueError, TypeError) as e: - logger.error( - f"Error processing coin data: {str(e)}" - ) - continue - - logger.info( - f"Successfully fetched data for {len(crypto_data)} coins" - ) - return crypto_data - - except Exception as e: - logger.error(f"Exception in get_market_data: {str(e)}") - return [] - - -class CryptoSwarmSystem: - def __init__(self): - self.agents = self._initialize_agents() - self.data_fetcher = DataFetcher() - logger.info("Crypto Swarm System initialized") - - def _initialize_agents(self) -> Dict[str, Agent]: - """Initialize different specialized agents""" - base_config = { - "max_loops": 1, - "autosave": True, - "dashboard": False, - "verbose": True, - "dynamic_temperature_enabled": True, - "retry_attempts": 3, - "context_length": 200000, - "return_step_meta": False, - "output_type": "string", - "streaming_on": False, - } - - agents = { - "price_analyst": Agent( - agent_name="Price-Analysis-Agent", - system_prompt="""Analyze the given cryptocurrency price data and provide insights about: - 1. Price trends and movements - 2. Notable price actions - 3. Potential support/resistance levels""", - saved_state_path="price_agent.json", - user_name="price_analyzer", - **base_config, - ), - "volume_analyst": Agent( - agent_name="Volume-Analysis-Agent", - system_prompt="""Analyze the given cryptocurrency volume data and provide insights about: - 1. Volume trends - 2. Notable volume spikes - 3. Market participation levels""", - saved_state_path="volume_agent.json", - user_name="volume_analyzer", - **base_config, - ), - "market_analyst": Agent( - agent_name="Market-Analysis-Agent", - system_prompt="""Analyze the overall cryptocurrency market data and provide insights about: - 1. Market trends - 2. Market dominance - 3. Notable market movements""", - saved_state_path="market_agent.json", - user_name="market_analyzer", - **base_config, - ), - } - return agents - - async def analyze_market(self) -> Dict: - """Run real-time market analysis using all agents""" - try: - # Fetch market data - logger.info("Fetching market data for top 20 coins") - crypto_data = await self.data_fetcher.get_market_data(20) - - if not crypto_data: - return { - "error": "Failed to fetch market data", - "timestamp": datetime.now().isoformat(), - } - - # Run analysis with each agent - results = {} - for agent_name, agent in self.agents.items(): - logger.info(f"Running {agent_name} analysis") - analysis = self._run_agent_analysis( - agent, crypto_data - ) - results[agent_name] = analysis - - return { - "timestamp": datetime.now().isoformat(), - "market_data": { - coin.symbol: { - "price": coin.current_price, - "market_cap": coin.market_cap, - "volume": coin.total_volume, - "price_change_24h": coin.price_change_24h, - "rank": coin.market_cap_rank, - } - for coin in crypto_data - }, - "analysis": results, - } - - except Exception as e: - logger.error(f"Error in market analysis: {str(e)}") - return { - "error": str(e), - "timestamp": datetime.now().isoformat(), - } - - def _run_agent_analysis( - self, agent: Agent, crypto_data: List[CryptoData] - ) -> str: - """Run analysis for a single agent""" - try: - data_str = json.dumps( - [ - { - "symbol": cd.symbol, - "price": cd.current_price, - "market_cap": cd.market_cap, - "volume": cd.total_volume, - "price_change_24h": cd.price_change_24h, - "rank": cd.market_cap_rank, - } - for cd in crypto_data - ], - indent=2, - ) - - prompt = f"""Analyze this real-time cryptocurrency market data and provide detailed insights: - {data_str}""" - - return agent.run(prompt) - - except Exception as e: - logger.error(f"Error in {agent.agent_name}: {str(e)}") - return f"Error: {str(e)}" - - -async def main(): - # Create output directory - Path("reports").mkdir(exist_ok=True) - - # Initialize the swarm system - swarm = CryptoSwarmSystem() - - while True: - try: - # Run analysis - report = await swarm.analyze_market() - - # Save report - timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") - report_path = f"reports/market_analysis_{timestamp}.json" - - with open(report_path, "w") as f: - json.dump(report, f, indent=2, default=str) - - logger.info( - f"Analysis complete. Report saved to {report_path}" - ) - - # Wait before next analysis - await asyncio.sleep(300) # 5 minutes - - except Exception as e: - logger.error(f"Error in main loop: {str(e)}") - await asyncio.sleep(60) # Wait 1 minute before retrying - finally: - if swarm.data_fetcher.session: - await swarm.data_fetcher.close() - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/new_features_examples/markdown_agent.py b/new_features_examples/markdown_agent.py deleted file mode 100644 index 51e15a97..00000000 --- a/new_features_examples/markdown_agent.py +++ /dev/null @@ -1,8 +0,0 @@ -from swarms import Agent - -Agent( - agent_name="Stock-Analysis-Agent", - model_name="gpt-4o-mini", - max_loops=1, - streaming_on=True, -).run("What are 5 hft algorithms") diff --git a/new_features_examples/medical_analysis/medical_analysis_agent_rearrange.md b/new_features_examples/medical_analysis/medical_analysis_agent_rearrange.md deleted file mode 100644 index 1f180c40..00000000 --- a/new_features_examples/medical_analysis/medical_analysis_agent_rearrange.md +++ /dev/null @@ -1,209 +0,0 @@ -Agent Name: Chief Medical Officer - Output: **Initial Assessment:** - -The patient is a 45-year-old female presenting with fever, dry cough, fatigue, and mild shortness of breath. She has a medical history of controlled hypertension, is fully vaccinated for COVID-19, and reports no recent travel or known sick contacts. These symptoms are nonspecific but could be indicative of a viral respiratory infection. - -**Differential Diagnoses:** - -1. **Influenza:** Given the time of year (December), influenza is a possibility, especially with symptoms like fever, cough, and fatigue. Vaccination status for influenza should be checked. - -2. **COVID-19:** Despite being fully vaccinated, breakthrough infections can occur. The symptoms align with COVID-19, and testing should be considered. - -3. **Respiratory Syncytial Virus (RSV):** RSV can present with similar symptoms in adults, especially those with underlying health conditions like hypertension. - -4. **Common Cold (Rhinovirus):** Although less likely given the fever, it is still a consideration. - -5. **Other Viral Infections:** Adenovirus, parainfluenza, and human metapneumovirus could also present with these symptoms. - -**Specialist Consultations Needed:** - -- **Infectious Disease Specialist:** To help narrow down the viral causes and suggest specific tests. -- **Pulmonologist:** Given the mild shortness of breath, a pulmonologist could provide insights into any underlying respiratory issues or complications. - -**Recommended Next Steps:** - -1. **Diagnostic Testing:** - - Perform a rapid influenza test. - - Conduct a COVID-19 PCR test to rule out a breakthrough infection. - - Consider a respiratory viral panel to detect other viruses like RSV or adenovirus. - -2. **Symptom Management:** - - Recommend supportive care including hydration, rest, and antipyretics (e.g., acetaminophen) for fever. - -3. **Monitoring:** - - Advise the patient to monitor symptoms closely, especially the shortness of breath, and seek immediate care if symptoms worsen. - -4. **Review Vaccination History:** - - Confirm influenza vaccination status for this season. - -5. **Follow-Up:** - - Schedule a follow-up appointment to review test results and adjust the treatment plan as necessary. - -**Limitations/Uncertainties:** - -- The absence of known sick contacts and travel history makes exposure assessment challenging. -- The possibility of co-infection with multiple viruses or secondary bacterial infection should be considered if symptoms worsen or do not improve with initial management. Agent Name: Virologist - Output: **Detailed Analysis:** - -**Characteristic Viral Symptoms:** - -1. **Influenza:** Typically presents with sudden onset of high fever, cough, sore throat, muscle aches, fatigue, and headache. The dry cough and fatigue in this patient are consistent with influenza, but muscle aches and sore throat are not mentioned. - -2. **COVID-19:** Symptoms can vary widely but often include fever, cough, fatigue, shortness of breath, and loss of taste or smell. The patient's symptoms align well with COVID-19, though the absence of anosmia (loss of smell) is noted. - -3. **RSV:** In adults, RSV often presents with mild cold-like symptoms such as cough, fever, and fatigue. Shortness of breath can occur, especially in those with pre-existing conditions. - -4. **Common Cold (Rhinovirus):** Typically causes milder symptoms like runny nose, cough, and sore throat. Fever is less common, making it a less likely primary cause in this case. - -5. **Other Viral Infections:** Adenovirus and human metapneumovirus can present with respiratory symptoms similar to those of influenza and COVID-19, including fever and cough. - -**Disease Progression Timeline:** - -- **Influenza:** Symptoms usually appear 1-4 days after exposure and can last for about a week, with cough and fatigue potentially persisting longer. -- **COVID-19:** Incubation period ranges from 2-14 days, with symptoms lasting from a few days to weeks depending on severity. -- **RSV:** Incubation is 4-6 days, and symptoms typically last 1-2 weeks. -- **Common Cold:** Symptoms usually appear 1-3 days after exposure and last about 7-10 days. - -**Risk Factors for Severe Disease:** - -- Controlled hypertension may increase the risk of complications from respiratory viruses like influenza and COVID-19. -- Age (45 years) is not a significant risk factor for severe disease, but vigilance is needed. -- The absence of other chronic conditions or immunosuppression reduces the risk of severe outcomes. - -**Potential Complications:** - -- **Influenza:** Can lead to pneumonia, bronchitis, or exacerbation of chronic conditions. -- **COVID-19:** Risk of pneumonia, acute respiratory distress syndrome (ARDS), and long COVID symptoms. -- **RSV:** Can cause bronchitis or pneumonia, particularly in older adults with underlying health issues. -- **Common Cold:** Rarely leads to complications, but secondary bacterial infections are possible. - -**Recommendations:** - -1. **Diagnostic Testing:** - - Rapid influenza and COVID-19 PCR tests are appropriate initial steps. - - A respiratory viral panel can provide a comprehensive assessment for other viral pathogens like RSV and adenovirus. - -2. **Symptom Management:** - - Supportive care remains crucial. Hydration, rest, and antipyretics are recommended. - - Consider cough suppressants or expectorants if cough is bothersome. - -3. **Monitoring and Follow-Up:** - - Close monitoring of symptoms, particularly shortness of breath, is essential. - - Follow-up should be scheduled to review test results and adjust treatment. - -4. **Vaccination Review:** - - Confirm influenza vaccination status and encourage vaccination if not already received. - -5. **Consideration of Co-Infections:** - - Be vigilant for signs of bacterial superinfection, particularly if symptoms worsen or do not improve with initial management. - -**Epidemiological Considerations:** - -- Seasonal factors (December) increase the likelihood of influenza and RSV. -- Current COVID-19 variants should be considered, even in vaccinated individuals. -- Geographic prevalence and local outbreak data can provide additional context for risk assessment. Agent Name: Internist - Output: **Internal Medicine Analysis:** - -**1. Vital Signs and Their Implications:** - - **Temperature:** Elevated temperature would suggest an active infection or inflammatory process. - - **Blood Pressure:** Controlled hypertension is noted, which could predispose the patient to complications from respiratory infections. - - **Heart Rate:** Tachycardia can be a response to fever or infection. - - **Respiratory Rate and Oxygen Saturation:** Increased respiratory rate or decreased oxygen saturation may indicate respiratory distress or hypoxemia, particularly in the context of viral infections like COVID-19 or influenza. - -**2. System-by-System Review:** - - - **Cardiovascular:** - - Monitor for signs of myocarditis or pericarditis, which can be complications of viral infections. - - Controlled hypertension should be managed to minimize cardiovascular stress. - - - **Respiratory:** - - Assess for signs of pneumonia or bronchitis, common complications of viral infections. - - Shortness of breath is a critical symptom that may indicate lower respiratory tract involvement. - - - **Neurological:** - - Fatigue and headache are common in viral illnesses but monitor for any signs of neurological involvement. - - - **Musculoskeletal:** - - Absence of muscle aches reduces the likelihood of influenza but does not rule it out. - -**3. Impact of Existing Medical Conditions:** - - Controlled hypertension may increase the risk of complications from respiratory infections. - - No other chronic conditions or immunosuppression are noted, which reduces the risk of severe outcomes. - -**4. Medication Interactions and Contraindications:** - - Review any current medications for potential interactions with antiviral or symptomatic treatments. - - Ensure medications for hypertension do not exacerbate respiratory symptoms or interact with treatments for the viral infection. - -**5. Risk Stratification:** - - Age (45 years) is not a significant risk factor for severe disease but requires vigilance. - - Controlled hypertension is a relevant risk factor for complications. - - Absence of other chronic conditions suggests a lower risk for severe outcomes. - -**Physical Examination Findings:** - - Focus on respiratory examination for signs of distress, consolidation, or wheezing. - - Cardiovascular examination should assess for any signs of increased workload or complications. - - General examination should assess for signs of systemic involvement or secondary bacterial infection. - -**System-Specific Symptoms:** - - Respiratory: Cough, shortness of breath. - - General: Fatigue, fever. - - Neurological: Headache. - -**Relevant Lab Abnormalities:** - - Elevated inflammatory markers (CRP, ESR) may indicate an active infection. - - CBC may show leukocytosis or lymphopenia, common in viral infections. - - Abnormal liver function tests could indicate systemic involvement. - -**Risk Factors for Complications:** - - Controlled hypertension. - - Potential for bacterial superinfection if symptoms worsen or do not improve. - -**Recommendations:** - - **Diagnostic Testing:** Rapid influenza and COVID-19 tests, respiratory viral panel if needed. - - **Symptom Management:** Supportive care, hydration, rest, antipyretics, cough suppressants if needed. - - **Monitoring and Follow-Up:** Monitor respiratory symptoms closely, schedule follow-up for test results and treatment adjustment. - - **Vaccination Review:** Confirm influenza vaccination status. - - **Consideration of Co-Infections:** Be vigilant for bacterial superinfection signs. - -**Epidemiological Considerations:** - - Seasonal factors and current viral prevalence should guide diagnostic suspicion and management. Agent Name: Diagnostic Synthesizer - Output: **Final Diagnostic Assessment** - -**1. Primary Diagnosis with Confidence Level:** - - **Viral Respiratory Infection (likely COVID-19 or Influenza):** Confidence Level: Moderate to High - - Based on the presence of fever, cough, shortness of breath, fatigue, and elevated inflammatory markers, a viral respiratory infection is the most probable diagnosis. The seasonality and current prevalence of COVID-19 and influenza further support this diagnosis. - -**2. Supporting Evidence Summary:** - - **Clinical Presentation:** Fever, cough, shortness of breath, fatigue, and headache are indicative of a viral infection. - - **Vital Signs:** Tachycardia and potential respiratory distress align with an active infection. - - **Lab Abnormalities:** Elevated CRP/ESR and possible leukocytosis or lymphopenia are common in viral infections. - - **Epidemiological Factors:** Current high prevalence of COVID-19 and influenza. - -**3. Alternative Diagnoses to Consider:** - - **Bacterial Pneumonia:** Consider if symptoms persist or worsen, particularly if there is consolidation on examination or imaging. - - **Myocarditis or Pericarditis:** These are potential complications of viral infections, especially if there are cardiovascular symptoms or abnormalities. - - **Non-Infectious Causes:** Less likely given the acute presentation but consider if symptoms do not resolve with typical viral course. - -**4. Recommended Confirmatory Tests:** - - **Rapid Influenza Test** - - **COVID-19 PCR or Antigen Test** - - **Respiratory Viral Panel:** If initial tests are negative and symptoms persist. - - **Chest X-ray or CT Scan:** If there is suspicion of pneumonia or other complications. - -**5. Red Flags or Warning Signs:** - - Worsening shortness of breath or persistent hypoxemia. - - Chest pain or signs of cardiovascular involvement. - - Persistent high fever or new onset of symptoms indicating a secondary bacterial infection. - -**6. Follow-up Recommendations:** - - **Symptom Monitoring:** Close monitoring of respiratory symptoms and general condition. - - **Follow-up Appointment:** Schedule follow-up to review test results and adjust treatment as necessary. - - **Vaccination Status:** Ensure influenza vaccination is up to date and consider COVID-19 booster if eligible. - - **Patient Education:** Inform about signs of worsening condition and when to seek immediate care. - -**Documentation Requirements:** -- **Reasoning Chain:** The diagnosis is based on clinical presentation, lab findings, and current epidemiological data. -- **Evidence Quality Assessment:** Moderate to high confidence based on reliable clinical and laboratory evidence. -- **Confidence Levels for Each Diagnosis:** Primary diagnosis is given moderate to high confidence, while alternatives are considered with lower probability unless symptoms evolve. -- **Knowledge Gaps Identified:** Awaiting confirmatory testing results to solidify the diagnosis. -- **Risk Assessment:** Controlled hypertension presents a moderate risk for complications, necessitating vigilant monitoring. \ No newline at end of file diff --git a/new_features_examples/medical_analysis/medical_coder_agent.py b/new_features_examples/medical_analysis/medical_coder_agent.py deleted file mode 100644 index 954c3718..00000000 --- a/new_features_examples/medical_analysis/medical_coder_agent.py +++ /dev/null @@ -1,248 +0,0 @@ -""" -- 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 -- 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 -> -- how to manage diseases and by looking at correlating lab, docs, diagnoses -- 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, -> -- fda api for healthcare for commerically available papers -- - -""" - -from datetime import datetime - -from swarms import Agent, AgentRearrange, create_file_in_folder - -chief_medical_officer = Agent( - agent_name="Chief Medical Officer", - system_prompt="""You are the Chief Medical Officer coordinating a team of medical specialists for viral disease diagnosis. - Your responsibilities include: - - Gathering initial patient symptoms and medical history - - Coordinating with specialists to form differential diagnoses - - Synthesizing different specialist opinions into a cohesive diagnosis - - Ensuring all relevant symptoms and test results are considered - - Making final diagnostic recommendations - - 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, -) - -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 - * Suspected viral conditions - * Associated symptoms - * Complications - - 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, -) - -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 - * Secondary diagnoses - * Complications - * 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, -) - -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 - - Description - - Supporting documentation - 2. Secondary Diagnosis Codes - - Listed in order of clinical significance - 3. Symptom Codes - 4. Complication Codes - 5. Coding Notes""", - model_name="gpt-4o", - max_loops=1, -) - -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 - - Secondary diagnoses with ICD-10 - - Supporting evidence - 2. Coding Summary - - Complete code list with descriptions - - Code hierarchy and relationships - - Supporting documentation - 3. Recommendations - - 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, -) - -# Create agent list -agents = [ - chief_medical_officer, - virologist, - internist, - medical_coder, - synthesizer, -] - -# Define diagnostic flow -flow = f"""{chief_medical_officer.agent_name} -> {virologist.agent_name} -> {internist.agent_name} -> {medical_coder.agent_name} -> {synthesizer.agent_name}""" - -# Create the swarm system -diagnosis_system = AgentRearrange( - name="Medical-coding-diagnosis-swarm", - description="Comprehensive medical diagnosis and coding system", - agents=agents, - flow=flow, - max_loops=1, - output_type="all", -) - - -def generate_coding_report(diagnosis_output: str) -> str: - """ - Generate a structured medical coding report from the diagnosis output. - """ - timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") - - report = f"""# Medical Diagnosis and Coding Report - Generated: {timestamp} - - ## Clinical Summary - {diagnosis_output} - - ## Coding Summary - ### Primary Diagnosis Codes - [Extracted from synthesis] - - ### Secondary Diagnosis Codes - [Extracted from synthesis] - - ### Symptom Codes - [Extracted from synthesis] - - ### Procedure Codes (if applicable) - [Extracted from synthesis] - - ## Documentation and Compliance Notes - - Code justification - - Supporting documentation references - - Any coding queries or clarifications needed - - ## Recommendations - - Additional documentation needed - - Suggested follow-up - - Coding optimization opportunities - """ - return report - - -if __name__ == "__main__": - # Example patient case - patient_case = """ - Patient: 45-year-old White Male - - Lab Results: - - egfr - - 59 ml / min / 1.73 - - non african-american - - """ - - # Add timestamp to the patient case - case_info = f"Timestamp: {datetime.now()}\nPatient Information: {patient_case}" - - # Run the diagnostic process - diagnosis = diagnosis_system.run(case_info) - - # Generate coding report - coding_report = generate_coding_report(diagnosis) - - # Create reports - create_file_in_folder( - "reports", "medical_diagnosis_report.md", diagnosis - ) - create_file_in_folder( - "reports", "medical_coding_report.md", coding_report - ) diff --git a/new_features_examples/medical_analysis/medical_coding_report.md b/new_features_examples/medical_analysis/medical_coding_report.md deleted file mode 100644 index 67f436e8..00000000 --- a/new_features_examples/medical_analysis/medical_coding_report.md +++ /dev/null @@ -1,342 +0,0 @@ -# Medical Diagnosis and Coding Report - Generated: 2024-12-09 11:17:38 - - ## Clinical Summary - Agent Name: Chief Medical Officer - Output: **Initial Assessment** - -- **Patient Information**: 45-year-old White Male -- **Key Lab Result**: - - eGFR (Estimated Glomerular Filtration Rate): 59 ml/min/1.73 m² -- **Preliminary ICD-10 Codes for Symptoms**: - - N18.3: Chronic kidney disease, stage 3 (moderate) - -**Differential Diagnoses** - -1. **Chronic Kidney Disease (CKD)** - - **ICD-10 Code**: N18.3 - - **Minimum Lab Range**: eGFR 30-59 ml/min/1.73 m² (indicative of stage 3 CKD) - - **Maximum Lab Range**: eGFR 59 ml/min/1.73 m² - -2. **Possible Acute Kidney Injury (AKI) on Chronic Kidney Disease** - - **ICD-10 Code**: N17.9 (Acute kidney failure, unspecified) superimposed on N18.3 - - **Minimum Lab Range**: Rapid decline in eGFR or increase in serum creatinine - - **Maximum Lab Range**: Dependent on baseline kidney function and rapidity of change - -3. **Hypertensive Nephropathy** - - **ICD-10 Code**: I12.9 (Hypertensive chronic kidney disease with stage 1 through stage 4 chronic kidney disease, or unspecified chronic kidney disease) - - **Minimum Lab Range**: eGFR 30-59 ml/min/1.73 m² with evidence of hypertension - - **Maximum Lab Range**: eGFR 59 ml/min/1.73 m² - -**Specialist Consultations Needed** - -- **Nephrologist**: To assess the kidney function and evaluate for CKD or other renal pathologies. -- **Cardiologist**: If hypertensive nephropathy is suspected, to manage associated cardiovascular risks and blood pressure. -- **Endocrinologist**: If there are any signs of diabetes or metabolic syndrome contributing to renal impairment. - -**Recommended Next Steps** - -1. **Detailed Medical History and Physical Examination**: - - Assess for symptoms such as fatigue, swelling, changes in urination, or hypertension. - - Review any history of diabetes, hypertension, or cardiovascular disease. - -2. **Additional Laboratory Tests**: - - Serum creatinine and blood urea nitrogen (BUN) to further evaluate kidney function. - - Urinalysis to check for proteinuria or hematuria. - - Lipid profile and fasting glucose to assess for metabolic syndrome. - -3. **Imaging Studies**: - - Renal ultrasound to evaluate kidney size and rule out obstructive causes. - -4. **Blood Pressure Monitoring**: - - Regular monitoring to assess for hypertension which could contribute to kidney damage. - -5. **Referral to Nephrology**: - - For comprehensive evaluation and management of kidney disease. - -6. **Patient Education**: - - Discuss lifestyle modifications such as diet, exercise, and smoking cessation to slow the progression of kidney disease. - -By following these steps, we can ensure a thorough evaluation of the patient's condition and formulate an appropriate management plan. Agent Name: Virologist - Output: **Clinical Analysis for Viral Diseases** - -Given the current patient information, there is no direct indication of a viral disease from the provided data. However, if a viral etiology is suspected or confirmed, the following analysis can be applied: - -### Clinical Analysis: -- **Detailed Viral Symptom Analysis**: - - Symptoms of viral infections can be diverse but often include fever, fatigue, muscle aches, and respiratory symptoms such as cough or sore throat. In the context of renal impairment, certain viral infections can lead to or exacerbate kidney issues, such as Hepatitis B or C, HIV, or cytomegalovirus (CMV). - -- **Disease Progression Timeline**: - - Viral infections typically have an incubation period ranging from a few days to weeks. The acute phase can last from several days to weeks, with symptoms peaking and then gradually resolving. Chronic viral infections, such as Hepatitis B or C, can lead to long-term complications, including kidney damage. - -- **Risk Factors and Complications**: - - Risk factors for viral infections include immunosuppression, exposure to infected individuals, travel history, and underlying health conditions. Complications can include acute kidney injury, chronic kidney disease progression, and systemic involvement leading to multi-organ dysfunction. - -### Coding Requirements: - -#### Relevant ICD-10 Codes: - -- **Confirmed Viral Conditions**: - - **B18.1**: Chronic viral hepatitis B - - **B18.2**: Chronic viral hepatitis C - - **B20**: HIV disease resulting in infectious and parasitic diseases - -- **Suspected Viral Conditions**: - - **B34.9**: Viral infection, unspecified - -- **Associated Symptoms**: - - **R50.9**: Fever, unspecified - - **R53.83**: Other fatigue - - **R05**: Cough - -- **Complications**: - - **N17.9**: Acute kidney failure, unspecified (if viral infection leads to AKI) - - **N18.9**: Chronic kidney disease, unspecified (if progression due to viral infection) - -#### Primary and Secondary Diagnostic Codes: - -- **Primary Diagnostic Codes**: - - Use the specific viral infection code as primary if confirmed (e.g., B18.2 for Hepatitis C). - -- **Secondary Condition Codes**: - - Use codes for symptoms or complications as secondary (e.g., N17.9 for AKI if due to viral infection). - -### Rationale for Code Selection: - -- **B18.1 and B18.2**: Selected for confirmed chronic hepatitis B or C, which can have renal complications. -- **B20**: Used if HIV is confirmed, given its potential impact on renal function. -- **B34.9**: Utilized when a viral infection is suspected but not yet identified. -- **R50.9, R53.83, R05**: Common symptoms associated with viral infections. -- **N17.9, N18.9**: Codes for renal complications potentially exacerbated by viral infections. - -### Documentation: - -- Ensure thorough documentation of clinical findings, suspected or confirmed viral infections, and associated symptoms or complications to justify the selected ICD-10 codes. -- Follow-up with additional testing or specialist referrals as needed to confirm or rule out viral etiologies and manage complications effectively. Agent Name: Internist - Output: To provide a comprehensive evaluation as an Internal Medicine specialist, let's conduct a detailed clinical assessment and medical coding for the presented case. This will involve a system-by-system review, analysis of vital signs, and evaluation of comorbidities, followed by appropriate ICD-10 coding. - -### Clinical Assessment: - -#### System-by-System Review: -1. **Respiratory System:** - - Evaluate for symptoms such as cough, shortness of breath, or wheezing. - - Consider potential viral or bacterial infections affecting the respiratory tract. - -2. **Cardiovascular System:** - - Assess for any signs of heart failure or hypertension. - - Look for symptoms like chest pain, palpitations, or edema. - -3. **Gastrointestinal System:** - - Check for symptoms such as nausea, vomiting, diarrhea, or abdominal pain. - - Consider liver function if hepatitis is suspected. - -4. **Renal System:** - - Monitor for signs of acute kidney injury or chronic kidney disease. - - Evaluate urine output and creatinine levels. - -5. **Neurological System:** - - Assess for headaches, dizziness, or any focal neurological deficits. - - Consider viral encephalitis if neurological symptoms are present. - -6. **Musculoskeletal System:** - - Look for muscle aches or joint pain, common in viral infections. - -7. **Integumentary System:** - - Check for rashes or skin lesions, which may indicate viral infections like herpes or CMV. - -8. **Immune System:** - - Consider immunosuppression status, especially in the context of HIV or other chronic infections. - -#### Vital Signs Analysis: -- **Temperature:** Evaluate for fever, which may indicate an infection. -- **Blood Pressure:** Check for hypertension or hypotension. -- **Heart Rate:** Assess for tachycardia or bradycardia. -- **Respiratory Rate:** Monitor for tachypnea. -- **Oxygen Saturation:** Ensure adequate oxygenation, especially in respiratory infections. - -#### Comorbidity Evaluation: -- Assess for chronic conditions such as diabetes, hypertension, or chronic kidney disease. -- Consider the impact of these conditions on the current clinical presentation and potential complications. - -### Medical Coding: - -#### ICD-10 Codes: - -1. **Primary Conditions:** - - If a specific viral infection is confirmed, use the appropriate code (e.g., B18.2 for chronic hepatitis C). - -2. **Secondary Diagnoses:** - - **B34.9:** Viral infection, unspecified (if viral etiology is suspected but not confirmed). - - **R50.9:** Fever, unspecified (common symptom in infections). - - **R53.83:** Other fatigue (common in viral infections). - -3. **Complications:** - - **N17.9:** Acute kidney failure, unspecified (if there is renal involvement). - - **N18.9:** Chronic kidney disease, unspecified (if there is progression due to infection). - -4. **Chronic Conditions:** - - **I10:** Essential (primary) hypertension (if present). - - **E11.9:** Type 2 diabetes mellitus without complications (if present). - -5. **Signs and Symptoms:** - - **R05:** Cough (common respiratory symptom). - - **M79.1:** Myalgia (muscle pain). - -#### Hierarchical Condition Category (HCC) Codes: -- **HCC 18:** Diabetes with chronic complications (if applicable). -- **HCC 85:** Congestive heart failure (if applicable). - -### Documentation Supporting Evidence: -- Ensure documentation includes detailed clinical findings, symptoms, and any laboratory or imaging results that support the diagnosis. -- Include any history of chronic conditions or recent changes in health status. -- Document any suspected or confirmed viral infections, along with their impact on the patient's health. - -### Conclusion: -This comprehensive evaluation and coding approach allows for accurate diagnosis and management of the patient's condition, considering both acute and chronic aspects of their health. Proper documentation and coding facilitate effective communication and continuity of care. Agent Name: Medical Coder - Output: ### Medical Coding Summary - -#### 1. Primary Diagnosis Codes -- **ICD-10 Code:** B18.2 - - **Description:** Chronic viral hepatitis C - - **Supporting Documentation:** The diagnosis of chronic hepatitis C is confirmed through serological testing and liver function tests indicating chronic viral infection. - -#### 2. Secondary Diagnosis Codes -- **B34.9:** Viral infection, unspecified - - **Supporting Documentation:** Suspected viral etiology without specific identification. -- **R50.9:** Fever, unspecified - - **Supporting Documentation:** Documented fever without a definitive cause. -- **R53.83:** Other fatigue - - **Supporting Documentation:** Patient reports persistent fatigue, common in viral infections. -- **I10:** Essential (primary) hypertension - - **Supporting Documentation:** History of hypertension with current blood pressure readings. -- **E11.9:** Type 2 diabetes mellitus without complications - - **Supporting Documentation:** Documented history of type 2 diabetes, managed with oral hypoglycemics. - -#### 3. Symptom Codes -- **R05:** Cough - - **Supporting Documentation:** Patient presents with a persistent cough, noted in the respiratory evaluation. -- **M79.1:** Myalgia - - **Supporting Documentation:** Patient reports muscle pain, consistent with viral infections. - -#### 4. Complication Codes -- **N17.9:** Acute kidney failure, unspecified - - **Supporting Documentation:** Elevated creatinine levels and reduced urine output indicative of renal involvement. -- **N18.9:** Chronic kidney disease, unspecified - - **Supporting Documentation:** Documented chronic kidney disease stage, with baseline creatinine levels. - -#### 5. Coding Notes -- Ensure all clinical findings and laboratory results supporting the diagnoses are documented in the patient's medical record. -- Confirm the presence of chronic conditions and their management strategies. -- Monitor for any changes in the patient's condition that may require code updates or additions. -- Address any coding queries related to unspecified viral infections by seeking further diagnostic clarification if possible. - -This coding summary provides a structured approach to documenting the patient's current health status, ensuring accurate and compliant ICD-10 coding. Agent Name: Diagnostic Synthesizer - Output: ### Final Diagnostic and Coding Assessment - -#### Clinical Summary - -**Primary Diagnosis:** -- **ICD-10 Code:** B18.2 - - **Description:** Chronic viral hepatitis C - - **Supporting Evidence:** This diagnosis is substantiated by serological testing and liver function tests indicating a chronic viral infection. The confidence level for this diagnosis is high, with high-quality evidence from laboratory results. - -**Secondary Diagnoses:** -1. **ICD-10 Code:** B34.9 - - **Description:** Viral infection, unspecified - - **Supporting Evidence:** The suspected viral etiology lacks specific identification. Confidence level is moderate due to limited specificity in viral identification. - -2. **ICD-10 Code:** R50.9 - - **Description:** Fever, unspecified - - **Supporting Evidence:** Documented fever without a definitive cause. Confidence level is moderate, supported by clinical observation. - -3. **ICD-10 Code:** R53.83 - - **Description:** Other fatigue - - **Supporting Evidence:** Patient reports persistent fatigue, often associated with viral infections. Confidence level is moderate, based on patient-reported symptoms. - -4. **ICD-10 Code:** I10 - - **Description:** Essential (primary) hypertension - - **Supporting Evidence:** History of hypertension corroborated by current blood pressure readings. Confidence level is high, with consistent clinical evidence. - -5. **ICD-10 Code:** E11.9 - - **Description:** Type 2 diabetes mellitus without complications - - **Supporting Evidence:** Managed with oral hypoglycemics, with a documented history. Confidence level is high, with strong management records. - -**Symptom Codes:** -- **ICD-10 Code:** R05 - - **Description:** Cough - - **Supporting Evidence:** Persistent cough noted in respiratory evaluation. Confidence level is moderate, based on clinical observation. - -- **ICD-10 Code:** M79.1 - - **Description:** Myalgia - - **Supporting Evidence:** Muscle pain reported by the patient, consistent with viral infections. Confidence level is moderate, based on patient-reported symptoms. - -**Complication Codes:** -1. **ICD-10 Code:** N17.9 - - **Description:** Acute kidney failure, unspecified - - **Supporting Evidence:** Elevated creatinine levels and reduced urine output suggest renal involvement. Confidence level is high, supported by laboratory data. - -2. **ICD-10 Code:** N18.9 - - **Description:** Chronic kidney disease, unspecified - - **Supporting Evidence:** Documented chronic kidney disease stage with baseline creatinine levels. Confidence level is high, with consistent clinical data. - -#### Coding Summary - -**Complete Code List with Descriptions:** -- B18.2: Chronic viral hepatitis C -- B34.9: Viral infection, unspecified -- R50.9: Fever, unspecified -- R53.83: Other fatigue -- I10: Essential (primary) hypertension -- E11.9: Type 2 diabetes mellitus without complications -- R05: Cough -- M79.1: Myalgia -- N17.9: Acute kidney failure, unspecified -- N18.9: Chronic kidney disease, unspecified - -**Code Hierarchy and Relationships:** -- The primary diagnosis (B18.2) is the central focus, with secondary diagnoses and symptoms potentially related to or exacerbated by the chronic hepatitis C infection. -- Complications (N17.9 and N18.9) may be linked to the primary diagnosis and other chronic conditions like diabetes and hypertension. - -**Supporting Documentation:** -- Ensure that all clinical findings and laboratory results supporting the diagnoses are documented in the patient's medical record. -- Confirm the presence of chronic conditions and their management strategies. -- Monitor for any changes in the patient's condition that may require code updates or additions. - -#### Recommendations - -1. **Additional Testing Needed:** - - Further diagnostic testing is recommended to clarify the unspecified viral infection (B34.9) and to monitor kidney function. - -2. **Follow-up Care:** - - Regular follow-up appointments to manage chronic conditions such as hypertension and diabetes. - - Monitor renal function and adjust treatment plans as necessary. - -3. **Documentation Improvements Needed:** - - Enhance documentation specificity for the unspecified viral infection. - - Ensure comprehensive records of all chronic conditions and their management strategies. - -These recommendations aim to improve diagnostic accuracy and patient care continuity. - - ## Coding Summary - ### Primary Diagnosis Codes - [Extracted from synthesis] - - ### Secondary Diagnosis Codes - [Extracted from synthesis] - - ### Symptom Codes - [Extracted from synthesis] - - ### Procedure Codes (if applicable) - [Extracted from synthesis] - - ## Documentation and Compliance Notes - - Code justification - - Supporting documentation references - - Any coding queries or clarifications needed - - ## Recommendations - - Additional documentation needed - - Suggested follow-up - - Coding optimization opportunities - \ No newline at end of file diff --git a/new_features_examples/medical_analysis/medical_diagnosis_report.md b/new_features_examples/medical_analysis/medical_diagnosis_report.md deleted file mode 100644 index f591f5c4..00000000 --- a/new_features_examples/medical_analysis/medical_diagnosis_report.md +++ /dev/null @@ -1,314 +0,0 @@ -Agent Name: Chief Medical Officer - Output: **Initial Assessment** - -- **Patient Information**: 45-year-old White Male -- **Key Lab Result**: - - eGFR (Estimated Glomerular Filtration Rate): 59 ml/min/1.73 m² -- **Preliminary ICD-10 Codes for Symptoms**: - - N18.3: Chronic kidney disease, stage 3 (moderate) - -**Differential Diagnoses** - -1. **Chronic Kidney Disease (CKD)** - - **ICD-10 Code**: N18.3 - - **Minimum Lab Range**: eGFR 30-59 ml/min/1.73 m² (indicative of stage 3 CKD) - - **Maximum Lab Range**: eGFR 59 ml/min/1.73 m² - -2. **Possible Acute Kidney Injury (AKI) on Chronic Kidney Disease** - - **ICD-10 Code**: N17.9 (Acute kidney failure, unspecified) superimposed on N18.3 - - **Minimum Lab Range**: Rapid decline in eGFR or increase in serum creatinine - - **Maximum Lab Range**: Dependent on baseline kidney function and rapidity of change - -3. **Hypertensive Nephropathy** - - **ICD-10 Code**: I12.9 (Hypertensive chronic kidney disease with stage 1 through stage 4 chronic kidney disease, or unspecified chronic kidney disease) - - **Minimum Lab Range**: eGFR 30-59 ml/min/1.73 m² with evidence of hypertension - - **Maximum Lab Range**: eGFR 59 ml/min/1.73 m² - -**Specialist Consultations Needed** - -- **Nephrologist**: To assess the kidney function and evaluate for CKD or other renal pathologies. -- **Cardiologist**: If hypertensive nephropathy is suspected, to manage associated cardiovascular risks and blood pressure. -- **Endocrinologist**: If there are any signs of diabetes or metabolic syndrome contributing to renal impairment. - -**Recommended Next Steps** - -1. **Detailed Medical History and Physical Examination**: - - Assess for symptoms such as fatigue, swelling, changes in urination, or hypertension. - - Review any history of diabetes, hypertension, or cardiovascular disease. - -2. **Additional Laboratory Tests**: - - Serum creatinine and blood urea nitrogen (BUN) to further evaluate kidney function. - - Urinalysis to check for proteinuria or hematuria. - - Lipid profile and fasting glucose to assess for metabolic syndrome. - -3. **Imaging Studies**: - - Renal ultrasound to evaluate kidney size and rule out obstructive causes. - -4. **Blood Pressure Monitoring**: - - Regular monitoring to assess for hypertension which could contribute to kidney damage. - -5. **Referral to Nephrology**: - - For comprehensive evaluation and management of kidney disease. - -6. **Patient Education**: - - Discuss lifestyle modifications such as diet, exercise, and smoking cessation to slow the progression of kidney disease. - -By following these steps, we can ensure a thorough evaluation of the patient's condition and formulate an appropriate management plan. Agent Name: Virologist - Output: **Clinical Analysis for Viral Diseases** - -Given the current patient information, there is no direct indication of a viral disease from the provided data. However, if a viral etiology is suspected or confirmed, the following analysis can be applied: - -### Clinical Analysis: -- **Detailed Viral Symptom Analysis**: - - Symptoms of viral infections can be diverse but often include fever, fatigue, muscle aches, and respiratory symptoms such as cough or sore throat. In the context of renal impairment, certain viral infections can lead to or exacerbate kidney issues, such as Hepatitis B or C, HIV, or cytomegalovirus (CMV). - -- **Disease Progression Timeline**: - - Viral infections typically have an incubation period ranging from a few days to weeks. The acute phase can last from several days to weeks, with symptoms peaking and then gradually resolving. Chronic viral infections, such as Hepatitis B or C, can lead to long-term complications, including kidney damage. - -- **Risk Factors and Complications**: - - Risk factors for viral infections include immunosuppression, exposure to infected individuals, travel history, and underlying health conditions. Complications can include acute kidney injury, chronic kidney disease progression, and systemic involvement leading to multi-organ dysfunction. - -### Coding Requirements: - -#### Relevant ICD-10 Codes: - -- **Confirmed Viral Conditions**: - - **B18.1**: Chronic viral hepatitis B - - **B18.2**: Chronic viral hepatitis C - - **B20**: HIV disease resulting in infectious and parasitic diseases - -- **Suspected Viral Conditions**: - - **B34.9**: Viral infection, unspecified - -- **Associated Symptoms**: - - **R50.9**: Fever, unspecified - - **R53.83**: Other fatigue - - **R05**: Cough - -- **Complications**: - - **N17.9**: Acute kidney failure, unspecified (if viral infection leads to AKI) - - **N18.9**: Chronic kidney disease, unspecified (if progression due to viral infection) - -#### Primary and Secondary Diagnostic Codes: - -- **Primary Diagnostic Codes**: - - Use the specific viral infection code as primary if confirmed (e.g., B18.2 for Hepatitis C). - -- **Secondary Condition Codes**: - - Use codes for symptoms or complications as secondary (e.g., N17.9 for AKI if due to viral infection). - -### Rationale for Code Selection: - -- **B18.1 and B18.2**: Selected for confirmed chronic hepatitis B or C, which can have renal complications. -- **B20**: Used if HIV is confirmed, given its potential impact on renal function. -- **B34.9**: Utilized when a viral infection is suspected but not yet identified. -- **R50.9, R53.83, R05**: Common symptoms associated with viral infections. -- **N17.9, N18.9**: Codes for renal complications potentially exacerbated by viral infections. - -### Documentation: - -- Ensure thorough documentation of clinical findings, suspected or confirmed viral infections, and associated symptoms or complications to justify the selected ICD-10 codes. -- Follow-up with additional testing or specialist referrals as needed to confirm or rule out viral etiologies and manage complications effectively. Agent Name: Internist - Output: To provide a comprehensive evaluation as an Internal Medicine specialist, let's conduct a detailed clinical assessment and medical coding for the presented case. This will involve a system-by-system review, analysis of vital signs, and evaluation of comorbidities, followed by appropriate ICD-10 coding. - -### Clinical Assessment: - -#### System-by-System Review: -1. **Respiratory System:** - - Evaluate for symptoms such as cough, shortness of breath, or wheezing. - - Consider potential viral or bacterial infections affecting the respiratory tract. - -2. **Cardiovascular System:** - - Assess for any signs of heart failure or hypertension. - - Look for symptoms like chest pain, palpitations, or edema. - -3. **Gastrointestinal System:** - - Check for symptoms such as nausea, vomiting, diarrhea, or abdominal pain. - - Consider liver function if hepatitis is suspected. - -4. **Renal System:** - - Monitor for signs of acute kidney injury or chronic kidney disease. - - Evaluate urine output and creatinine levels. - -5. **Neurological System:** - - Assess for headaches, dizziness, or any focal neurological deficits. - - Consider viral encephalitis if neurological symptoms are present. - -6. **Musculoskeletal System:** - - Look for muscle aches or joint pain, common in viral infections. - -7. **Integumentary System:** - - Check for rashes or skin lesions, which may indicate viral infections like herpes or CMV. - -8. **Immune System:** - - Consider immunosuppression status, especially in the context of HIV or other chronic infections. - -#### Vital Signs Analysis: -- **Temperature:** Evaluate for fever, which may indicate an infection. -- **Blood Pressure:** Check for hypertension or hypotension. -- **Heart Rate:** Assess for tachycardia or bradycardia. -- **Respiratory Rate:** Monitor for tachypnea. -- **Oxygen Saturation:** Ensure adequate oxygenation, especially in respiratory infections. - -#### Comorbidity Evaluation: -- Assess for chronic conditions such as diabetes, hypertension, or chronic kidney disease. -- Consider the impact of these conditions on the current clinical presentation and potential complications. - -### Medical Coding: - -#### ICD-10 Codes: - -1. **Primary Conditions:** - - If a specific viral infection is confirmed, use the appropriate code (e.g., B18.2 for chronic hepatitis C). - -2. **Secondary Diagnoses:** - - **B34.9:** Viral infection, unspecified (if viral etiology is suspected but not confirmed). - - **R50.9:** Fever, unspecified (common symptom in infections). - - **R53.83:** Other fatigue (common in viral infections). - -3. **Complications:** - - **N17.9:** Acute kidney failure, unspecified (if there is renal involvement). - - **N18.9:** Chronic kidney disease, unspecified (if there is progression due to infection). - -4. **Chronic Conditions:** - - **I10:** Essential (primary) hypertension (if present). - - **E11.9:** Type 2 diabetes mellitus without complications (if present). - -5. **Signs and Symptoms:** - - **R05:** Cough (common respiratory symptom). - - **M79.1:** Myalgia (muscle pain). - -#### Hierarchical Condition Category (HCC) Codes: -- **HCC 18:** Diabetes with chronic complications (if applicable). -- **HCC 85:** Congestive heart failure (if applicable). - -### Documentation Supporting Evidence: -- Ensure documentation includes detailed clinical findings, symptoms, and any laboratory or imaging results that support the diagnosis. -- Include any history of chronic conditions or recent changes in health status. -- Document any suspected or confirmed viral infections, along with their impact on the patient's health. - -### Conclusion: -This comprehensive evaluation and coding approach allows for accurate diagnosis and management of the patient's condition, considering both acute and chronic aspects of their health. Proper documentation and coding facilitate effective communication and continuity of care. Agent Name: Medical Coder - Output: ### Medical Coding Summary - -#### 1. Primary Diagnosis Codes -- **ICD-10 Code:** B18.2 - - **Description:** Chronic viral hepatitis C - - **Supporting Documentation:** The diagnosis of chronic hepatitis C is confirmed through serological testing and liver function tests indicating chronic viral infection. - -#### 2. Secondary Diagnosis Codes -- **B34.9:** Viral infection, unspecified - - **Supporting Documentation:** Suspected viral etiology without specific identification. -- **R50.9:** Fever, unspecified - - **Supporting Documentation:** Documented fever without a definitive cause. -- **R53.83:** Other fatigue - - **Supporting Documentation:** Patient reports persistent fatigue, common in viral infections. -- **I10:** Essential (primary) hypertension - - **Supporting Documentation:** History of hypertension with current blood pressure readings. -- **E11.9:** Type 2 diabetes mellitus without complications - - **Supporting Documentation:** Documented history of type 2 diabetes, managed with oral hypoglycemics. - -#### 3. Symptom Codes -- **R05:** Cough - - **Supporting Documentation:** Patient presents with a persistent cough, noted in the respiratory evaluation. -- **M79.1:** Myalgia - - **Supporting Documentation:** Patient reports muscle pain, consistent with viral infections. - -#### 4. Complication Codes -- **N17.9:** Acute kidney failure, unspecified - - **Supporting Documentation:** Elevated creatinine levels and reduced urine output indicative of renal involvement. -- **N18.9:** Chronic kidney disease, unspecified - - **Supporting Documentation:** Documented chronic kidney disease stage, with baseline creatinine levels. - -#### 5. Coding Notes -- Ensure all clinical findings and laboratory results supporting the diagnoses are documented in the patient's medical record. -- Confirm the presence of chronic conditions and their management strategies. -- Monitor for any changes in the patient's condition that may require code updates or additions. -- Address any coding queries related to unspecified viral infections by seeking further diagnostic clarification if possible. - -This coding summary provides a structured approach to documenting the patient's current health status, ensuring accurate and compliant ICD-10 coding. Agent Name: Diagnostic Synthesizer - Output: ### Final Diagnostic and Coding Assessment - -#### Clinical Summary - -**Primary Diagnosis:** -- **ICD-10 Code:** B18.2 - - **Description:** Chronic viral hepatitis C - - **Supporting Evidence:** This diagnosis is substantiated by serological testing and liver function tests indicating a chronic viral infection. The confidence level for this diagnosis is high, with high-quality evidence from laboratory results. - -**Secondary Diagnoses:** -1. **ICD-10 Code:** B34.9 - - **Description:** Viral infection, unspecified - - **Supporting Evidence:** The suspected viral etiology lacks specific identification. Confidence level is moderate due to limited specificity in viral identification. - -2. **ICD-10 Code:** R50.9 - - **Description:** Fever, unspecified - - **Supporting Evidence:** Documented fever without a definitive cause. Confidence level is moderate, supported by clinical observation. - -3. **ICD-10 Code:** R53.83 - - **Description:** Other fatigue - - **Supporting Evidence:** Patient reports persistent fatigue, often associated with viral infections. Confidence level is moderate, based on patient-reported symptoms. - -4. **ICD-10 Code:** I10 - - **Description:** Essential (primary) hypertension - - **Supporting Evidence:** History of hypertension corroborated by current blood pressure readings. Confidence level is high, with consistent clinical evidence. - -5. **ICD-10 Code:** E11.9 - - **Description:** Type 2 diabetes mellitus without complications - - **Supporting Evidence:** Managed with oral hypoglycemics, with a documented history. Confidence level is high, with strong management records. - -**Symptom Codes:** -- **ICD-10 Code:** R05 - - **Description:** Cough - - **Supporting Evidence:** Persistent cough noted in respiratory evaluation. Confidence level is moderate, based on clinical observation. - -- **ICD-10 Code:** M79.1 - - **Description:** Myalgia - - **Supporting Evidence:** Muscle pain reported by the patient, consistent with viral infections. Confidence level is moderate, based on patient-reported symptoms. - -**Complication Codes:** -1. **ICD-10 Code:** N17.9 - - **Description:** Acute kidney failure, unspecified - - **Supporting Evidence:** Elevated creatinine levels and reduced urine output suggest renal involvement. Confidence level is high, supported by laboratory data. - -2. **ICD-10 Code:** N18.9 - - **Description:** Chronic kidney disease, unspecified - - **Supporting Evidence:** Documented chronic kidney disease stage with baseline creatinine levels. Confidence level is high, with consistent clinical data. - -#### Coding Summary - -**Complete Code List with Descriptions:** -- B18.2: Chronic viral hepatitis C -- B34.9: Viral infection, unspecified -- R50.9: Fever, unspecified -- R53.83: Other fatigue -- I10: Essential (primary) hypertension -- E11.9: Type 2 diabetes mellitus without complications -- R05: Cough -- M79.1: Myalgia -- N17.9: Acute kidney failure, unspecified -- N18.9: Chronic kidney disease, unspecified - -**Code Hierarchy and Relationships:** -- The primary diagnosis (B18.2) is the central focus, with secondary diagnoses and symptoms potentially related to or exacerbated by the chronic hepatitis C infection. -- Complications (N17.9 and N18.9) may be linked to the primary diagnosis and other chronic conditions like diabetes and hypertension. - -**Supporting Documentation:** -- Ensure that all clinical findings and laboratory results supporting the diagnoses are documented in the patient's medical record. -- Confirm the presence of chronic conditions and their management strategies. -- Monitor for any changes in the patient's condition that may require code updates or additions. - -#### Recommendations - -1. **Additional Testing Needed:** - - Further diagnostic testing is recommended to clarify the unspecified viral infection (B34.9) and to monitor kidney function. - -2. **Follow-up Care:** - - Regular follow-up appointments to manage chronic conditions such as hypertension and diabetes. - - Monitor renal function and adjust treatment plans as necessary. - -3. **Documentation Improvements Needed:** - - Enhance documentation specificity for the unspecified viral infection. - - Ensure comprehensive records of all chronic conditions and their management strategies. - -These recommendations aim to improve diagnostic accuracy and patient care continuity. \ No newline at end of file diff --git a/new_features_examples/medical_analysis/new_medical_rearrange.py b/new_features_examples/medical_analysis/new_medical_rearrange.py deleted file mode 100644 index 0a7389bd..00000000 --- a/new_features_examples/medical_analysis/new_medical_rearrange.py +++ /dev/null @@ -1,177 +0,0 @@ -from datetime import datetime - -from swarms import Agent, AgentRearrange, create_file_in_folder - -chief_medical_officer = Agent( - agent_name="Chief Medical Officer", - system_prompt="""You are the Chief Medical Officer coordinating a team of medical specialists for viral disease diagnosis. - Your responsibilities include: - - Gathering initial patient symptoms and medical history - - Coordinating with specialists to form differential diagnoses - - Synthesizing different specialist opinions into a cohesive diagnosis - - Ensuring all relevant symptoms and test results are considered - - 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 - 3. Factor in patient demographics and risk factors - 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 - - Specialist Consultations Needed - - Recommended Next Steps""", - model_name="gpt-4o", # Models from litellm -> claude-2 - max_loops=1, -) - -# Viral Disease Specialist -virologist = Agent( - agent_name="Virologist", - system_prompt="""You are a specialist in viral diseases with expertise in: - - Respiratory viruses (Influenza, Coronavirus, RSV) - - 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 - - Seasonal factors - - Geographic prevalence - - Patient immune status - - Current viral outbreaks - - Provide detailed analysis of: - - Characteristic viral symptoms - - Disease progression timeline - - Risk factors for severe disease - - Potential complications""", - model_name="gpt-4o", - max_loops=1, -) - -# Internal Medicine Specialist -internist = Agent( - agent_name="Internist", - system_prompt="""You are an Internal Medicine specialist responsible for: - - Comprehensive system-based evaluation - - 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 - - Relevant lab abnormalities - - Risk factors for complications""", - model_name="gpt-4o", - max_loops=1, -) - -# Diagnostic Synthesizer -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 - 3. Alternative diagnoses to consider - 4. Recommended confirmatory tests - 5. Red flags or warning signs - 6. Follow-up recommendations - - Documentation requirements: - - Clear reasoning chain - - Evidence quality assessment - - Confidence levels for each diagnosis - - Knowledge gaps identified - - Risk assessment""", - model_name="gpt-4o", - max_loops=1, -) - -# Create agent list -agents = [chief_medical_officer, virologist, internist, synthesizer] - -# Define diagnostic flow -flow = f"""{chief_medical_officer.agent_name} -> {virologist.agent_name} -> {internist.agent_name} -> {synthesizer.agent_name}""" - -# Create the swarm system -diagnosis_system = AgentRearrange( - name="Medical-nlp-diagnosis-swarm", - description="natural language symptions to diagnosis report", - agents=agents, - flow=flow, - max_loops=1, - output_type="all", -) - - -# Example usage -if __name__ == "__main__": - # Example patient case - patient_case = """ - Patient: 45-year-old female - Presenting symptoms: - - Fever (101.5°F) for 3 days - - Dry cough - - Fatigue - - Mild shortness of breath - Medical history: - - Controlled hypertension - - No recent travel - - Fully vaccinated for COVID-19 - - No known sick contacts - """ - - # Add timestamp to the patient case - case_info = f"Timestamp: {datetime.now()}\nPatient Information: {patient_case}" - - # Run the diagnostic process - diagnosis = diagnosis_system.run(case_info) - - # Create a folder and file called reports - create_file_in_folder( - "reports", "medical_analysis_agent_rearrange.md", diagnosis - ) diff --git a/new_features_examples/medical_analysis/rearrange_video_examples/reports/medical_analysis_agent_rearrange.md b/new_features_examples/medical_analysis/rearrange_video_examples/reports/medical_analysis_agent_rearrange.md deleted file mode 100644 index d203c61f..00000000 --- a/new_features_examples/medical_analysis/rearrange_video_examples/reports/medical_analysis_agent_rearrange.md +++ /dev/null @@ -1,173 +0,0 @@ -**Initial Assessment:** - -The patient is a 45-year-old female presenting with a fever, dry cough, fatigue, and mild shortness of breath. Her medical history includes controlled hypertension. She has not traveled recently and has no known sick contacts. Additionally, she is fully vaccinated for COVID-19. - -**Differential Diagnoses:** - -1. **Influenza:** Given the season and symptoms, influenza is a strong possibility. The patient’s symptoms align well with typical flu presentations, which include fever, cough, and fatigue. - -2. **COVID-19:** Despite being fully vaccinated, breakthrough infections can occur, especially with new variants. Symptoms such as fever, cough, and shortness of breath are consistent with COVID-19. - -3. **Respiratory Syncytial Virus (RSV):** RSV can cause symptoms similar to those of the flu and COVID-19, including cough and shortness of breath, particularly in adults with underlying conditions. - -4. **Viral Pneumonia:** This could be a complication of an initial viral infection, presenting with fever, cough, and shortness of breath. - -5. **Other Viral Infections:** Other respiratory viruses, such as adenovirus or parainfluenza, could also be considered, though less common. - -**Specialist Consultations Needed:** - -1. **Infectious Disease Specialist:** To evaluate and prioritize testing for specific viral pathogens and to provide input on potential treatment plans. - -2. **Pulmonologist:** Given the mild shortness of breath and history of hypertension, a pulmonologist could assess the need for further respiratory evaluation or intervention. - -**Recommended Next Steps:** - -1. **Diagnostic Testing:** - - Perform a rapid influenza test and a COVID-19 PCR test to rule out these common viral infections. - - Consider a respiratory viral panel if initial tests are negative to identify other potential viral causes. - -2. **Symptomatic Treatment:** - - Recommend antipyretics for fever management. - - Encourage rest and hydration to help manage fatigue and overall symptoms. - -3. **Monitoring and Follow-Up:** - - Monitor respiratory symptoms closely, given the mild shortness of breath, and advise the patient to seek immediate care if symptoms worsen. - - Schedule a follow-up appointment to reassess symptoms and review test results. - -4. **Consideration of Antiviral Treatment:** - - If influenza is confirmed, consider antiviral treatment with oseltamivir, especially given the patient's age and comorbidities. - -**Limitations or Uncertainties:** - -- There is uncertainty regarding the exact viral cause without specific test results. -- The potential for atypical presentations or co-infections should be considered, particularly if initial tests are inconclusive. - -By following these steps, we aim to determine the underlying cause of the patient's symptoms and provide appropriate care. **Detailed Analysis:** - -1. **Characteristic Viral Symptoms:** - - **Influenza:** Typically presents with sudden onset of fever, chills, cough, sore throat, muscle or body aches, headaches, and fatigue. Shortness of breath can occur, especially if there is a progression to viral pneumonia. - - **COVID-19:** Symptoms can vary widely but often include fever, cough, fatigue, and shortness of breath. Loss of taste or smell, sore throat, and gastrointestinal symptoms may also occur. - - **RSV:** In adults, RSV can cause symptoms similar to a mild cold, but in some cases, it can lead to more severe respiratory symptoms, especially in those with underlying conditions. - - **Viral Pneumonia:** Often presents with persistent cough, fever, shortness of breath, and fatigue. It can be a complication of other respiratory viral infections. - - **Other Respiratory Viruses (e.g., Adenovirus, Parainfluenza):** These can cause a range of symptoms similar to the common cold or flu, including fever, cough, and congestion. - -2. **Disease Progression Timeline:** - - **Influenza:** Symptoms usually appear 1-4 days after exposure and can last for about a week, although cough and fatigue may persist longer. - - **COVID-19:** Symptoms typically appear 2-14 days after exposure, with a median of 5 days. The course can vary significantly, from mild to severe. - - **RSV:** Symptoms generally appear 4-6 days after exposure and can last 1-2 weeks. - - **Viral Pneumonia:** Can develop as a complication of a primary viral infection, often within a few days of the initial symptoms. - -3. **Risk Factors for Severe Disease:** - - **Influenza and COVID-19:** Age over 50, hypertension, and other comorbidities can increase the risk of severe disease. - - **RSV:** More severe in adults with chronic heart or lung disease or weakened immune systems. - - **Viral Pneumonia:** More likely in individuals with weakened immune systems or pre-existing respiratory conditions. - -4. **Potential Complications:** - - **Influenza:** Can lead to pneumonia, exacerbation of chronic medical conditions, and secondary bacterial infections. - - **COVID-19:** Complications can include pneumonia, acute respiratory distress syndrome (ARDS), organ failure, and long COVID. - - **RSV:** Can result in bronchiolitis or pneumonia, particularly in vulnerable populations. - - **Viral Pneumonia:** Can lead to respiratory failure and secondary bacterial infections. - -**Considerations for Testing and Monitoring:** -- Given the overlapping symptoms, initial testing for influenza and COVID-19 is crucial. -- A comprehensive respiratory viral panel can help identify less common viral pathogens if initial tests are negative. -- Monitoring for worsening respiratory symptoms is essential, given the patient's mild shortness of breath and history of hypertension. - -**Recommendations for Care:** -- Symptomatic treatment should focus on fever and symptom relief while awaiting test results. -- In the case of confirmed influenza, antiviral treatment with oseltamivir is advisable, especially due to the patient's age and hypertension. -- Close follow-up is necessary to reassess symptoms and ensure timely intervention if the patient's condition deteriorates. - -**Final Note:** -- Stay updated on current viral outbreaks and emerging variants, as these can influence the likelihood of specific viral infections and guide testing priorities. To proceed with a comprehensive internal medicine evaluation based on the virologist's analysis, we will assess the case systematically: - -1. **Vital Signs and Their Implications:** - - **Temperature:** Evaluate for fever, which can indicate an ongoing infection or inflammatory process. - - **Respiratory Rate:** Increased rate may suggest respiratory distress or compensation for hypoxemia. - - **Heart Rate and Blood Pressure:** Tachycardia or hypertension may indicate systemic stress or a response to fever/infection. - - **Oxygen Saturation:** Important to assess for hypoxemia, especially in respiratory infections. - -2. **System-by-System Review:** - - - **Cardiovascular:** Consider the impact of viral infections on the cardiovascular system, such as myocarditis or exacerbation of heart failure, especially in patients with hypertension or other comorbidities. - - **Respiratory:** Assess for signs of pneumonia or bronchitis. Auscultation may reveal crackles or wheezes. Consider chest imaging if indicated. - - **Gastrointestinal:** Evaluate for symptoms like nausea, vomiting, or diarrhea, which can occur with COVID-19 or other viral infections. - - **Neurological:** Monitor for headache, confusion, or loss of taste/smell, which can be associated with viral infections like COVID-19. - - **Musculoskeletal:** Assess for myalgias or arthralgias, common in influenza. - -3. **Impact of Existing Medical Conditions:** - - **Hypertension:** Monitor blood pressure closely, as viral infections can exacerbate hypertension. - - **Age-related Factors:** Older age increases the risk of severe disease and complications from viral infections. - - **Chronic Diseases:** Consider the impact of other chronic conditions, such as diabetes or COPD, which may complicate the clinical course. - -4. **Medication Interactions and Contraindications:** - - Review current medications for interactions with potential antiviral treatments, such as oseltamivir for influenza. - - Consider contraindications for specific treatments based on the patient's comorbidities. - -5. **Risk Stratification:** - - Assess the patient's risk for severe disease based on age, comorbidities, and current symptoms. - - Identify patients who may need more intensive monitoring or early intervention. - -**Documentation:** - -- **Physical Examination Findings:** - - Document vital signs, respiratory effort, and any abnormal findings on auscultation or other systems. - -- **System-Specific Symptoms:** - - Record symptoms such as cough, fever, fatigue, and any gastrointestinal or neurological symptoms. - -- **Relevant Lab Abnormalities:** - - Note any significant lab findings, such as elevated inflammatory markers or abnormal CBC. - -- **Risk Factors for Complications:** - - Highlight factors such as age, hypertension, and any other relevant comorbid conditions. - -**Plan:** -- Initiate appropriate symptomatic treatment while awaiting test results. -- Consider antiviral therapy if influenza is confirmed, particularly given the patient's age and hypertension. -- Ensure close follow-up to monitor for any deterioration in the patient's condition, and adjust the management plan as needed. -- Educate the patient on signs of worsening symptoms and when to seek further medical attention. - -By integrating these considerations, we can provide a holistic approach to the management of viral infections in the context of internal medicine. **Final Diagnostic Assessment** - -1. **Primary Diagnosis: Viral Respiratory Infection (e.g., Influenza or COVID-19)** - - **Confidence Level:** Moderate to High - - **Supporting Evidence Summary:** - - Presence of fever, cough, and respiratory symptoms. - - Possible gastrointestinal symptoms (nausea, vomiting, diarrhea). - - Neurological symptoms such as headache and potential anosmia. - - Elevated inflammatory markers and potential CBC abnormalities. - - Older age and hypertension increase risk for severe disease. - -2. **Alternative Diagnoses to Consider:** - - **Bacterial Pneumonia:** Consider if symptoms worsen or if there is a lack of improvement with antiviral treatment. - - **Heart Failure Exacerbation:** Especially if there are cardiovascular symptoms like edema or worsening dyspnea. - - **Other Viral Infections:** Such as RSV or adenovirus, particularly if COVID-19 and influenza tests are negative. - -3. **Recommended Confirmatory Tests:** - - PCR testing for COVID-19 and Influenza. - - Chest X-ray or CT scan if pneumonia is suspected. - - Blood cultures if bacterial infection is a concern. - - Complete blood count (CBC) and inflammatory markers for further assessment. - -4. **Red Flags or Warning Signs:** - - Rapid deterioration in respiratory status (e.g., increased work of breathing, hypoxemia). - - Signs of cardiovascular compromise (e.g., chest pain, severe hypertension). - - Neurological changes (e.g., confusion, severe headache). - - Persistent high fever despite treatment. - -5. **Follow-up Recommendations:** - - Close monitoring of vital signs and symptom progression. - - Re-evaluation within 48-72 hours or sooner if symptoms worsen. - - Adjust treatment plan based on test results and clinical response. - - Patient education on recognizing signs of complications and when to seek urgent care. - -**Documentation Requirements:** - -- **Clear Reasoning Chain:** The diagnosis is based on the synthesis of clinical symptoms, lab findings, and risk factors. -- **Evidence Quality Assessment:** Moderate quality; relies on clinical presentation and initial lab results. -- **Confidence Levels for Each Diagnosis:** Primary diagnosis (Viral Respiratory Infection) is moderate to high; alternative diagnoses are lower. -- **Knowledge Gaps Identified:** Awaiting confirmatory test results for specific viral or bacterial pathogens. -- **Risk Assessment:** High risk for complications due to age and hypertension; requires vigilant monitoring and timely intervention. - -By following this structured diagnostic framework, we ensure a comprehensive and patient-centered approach to managing the suspected viral respiratory infection while being prepared for alternative diagnoses and potential complications. \ No newline at end of file diff --git a/new_features_examples/medical_analysis/rearrange_video_examples/reports/vc_document_analysis.md b/new_features_examples/medical_analysis/rearrange_video_examples/reports/vc_document_analysis.md deleted file mode 100644 index 2348d4b4..00000000 --- a/new_features_examples/medical_analysis/rearrange_video_examples/reports/vc_document_analysis.md +++ /dev/null @@ -1,291 +0,0 @@ -**Executive Summary:** - -The document under review is a SAFE (Simple Agreement for Future Equity) agreement, which provides the investor with rights to convert their investment into equity under specified conditions. The key financial terms include a valuation cap of $10,000,000 and a discount rate of 20%. The investment amount is $500,000, with provisions for automatic and optional conversion, as well as pro-rata rights for future investment rounds. - -**Key Terms Analysis:** - -1. **Valuation Cap:** $10,000,000 - This sets the maximum valuation at which the investment will convert into equity. -2. **Discount Rate:** 20% - This provides the investor with a discount on the price per share during conversion. -3. **Investment Amount:** $500,000 - The amount invested under this agreement. -4. **Conversion Provisions:** - - **Automatic Conversion:** Triggers upon an equity financing round of at least $1,000,000. - - **Optional Conversion:** Available upon a liquidity event. - - **Most Favored Nation (MFN):** Ensures the investor receives terms no less favorable than those offered to subsequent investors. -5. **Pro-rata Rights:** Allows the investor to maintain their percentage ownership in future financing rounds. - -**Risk Factors:** - -1. **Valuation Cap Risk:** If the company's valuation exceeds $10,000,000 during conversion, the investor benefits from a lower conversion price, but if the valuation is below, the cap may not provide a significant advantage. -2. **Conversion Timing:** The automatic conversion depends on a future equity financing event, which introduces timing and market risk. -3. **MFN Clause Complexity:** The inclusion of an MFN clause can complicate future financing negotiations and may deter other investors. - -**Negotiation Points:** - -1. **Valuation Cap Adjustment:** Consider negotiating a lower valuation cap to provide better upside protection. -2. **Discount Rate Increase:** Explore increasing the discount rate to improve conversion terms. -3. **Clarification of MFN Terms:** Ensure clarity on the MFN provision to avoid potential disputes in future rounds. -4. **Pro-rata Rights Specification:** Detail the conditions under which pro-rata rights can be exercised, including any limitations or exceptions. - -**Recommended Actions:** - -1. **Review Market Comparables:** Assess current market conditions to ensure valuation cap and discount rate align with industry standards. -2. **Legal Review of MFN Clause:** Engage legal counsel to review the MFN provision for potential issues. -3. **Scenario Analysis:** Conduct a scenario analysis to understand the impact of various conversion events on equity ownership. - -**Areas Requiring Specialist Review:** - -1. **Legal Review:** A legal specialist should review the MFN provision and conversion clauses for enforceability and potential conflicts. -2. **Financial Modeling:** A financial analyst should model different conversion scenarios to assess potential outcomes and returns. -3. **Market Analysis:** A market specialist should evaluate the competitiveness of the valuation cap and discount rate based on current trends. **Detailed Analysis of SAFE Agreement** - -**1. Term-by-Term Analysis:** - -- **Valuation Cap ($10,000,000):** - - Sets a ceiling on the company’s valuation for conversion purposes. This cap provides the investor with protection in case the company's valuation at the time of conversion is higher than $10M, ensuring a more favorable conversion price. - - **Valuation Implications:** If the company's pre-money valuation is above $10M in a future financing round, the investor benefits from a lower effective price per share, potentially increasing their ownership percentage. - - **Recommendation:** Consider negotiating a lower cap if market conditions suggest the company might achieve a higher valuation soon. - -- **Discount Rate (20%):** - - Provides a reduction on the price per share during conversion, giving the investor a benefit compared to new investors in the subsequent round. - - **Valuation Implications:** Acts as a hedge against high valuations by ensuring a discount on the conversion price. - - **Recommendation:** Assess market standards to determine if a higher discount rate is achievable. - -- **Investment Amount ($500,000):** - - The principal amount invested, which will convert into equity under the agreed terms. - - **Future Round Impacts:** This amount will affect the company's cap table upon conversion, diluting existing shareholders. - - **Recommendation:** Ensure this aligns with the company’s capital needs and strategic goals. - -- **Conversion Provisions:** - - **Automatic Conversion:** Triggers upon an equity financing round of at least $1,000,000. - - **Conversion Mechanics:** The investment converts into equity automatically, based on the valuation cap or discount rate, whichever is more favorable. - - **Recommendation:** Ensure the threshold aligns with realistic fundraising expectations. - - **Optional Conversion:** Available upon a liquidity event, such as an acquisition or IPO. - - **Conversion Mechanics:** Provides flexibility for the investor to convert under favorable terms during liquidity events. - - **Recommendation:** Clearly define what constitutes a liquidity event to avoid ambiguity. - -- **Most Favored Nation (MFN) Provision:** - - **Investor Rights and Limitations:** Ensures the investor receives terms no less favorable than those offered to future investors. - - **Potential Conflicts:** This can complicate future rounds as new investors might demand the same or better terms. - - **Recommendation:** Clarify the scope and limitations of the MFN clause to avoid deterring future investors. - -- **Pro-rata Rights:** - - **Investor Rights:** Allows the investor to maintain their ownership percentage in future financing rounds by purchasing additional shares. - - **Recommendation:** Specify the conditions and limitations under which these rights can be exercised to avoid potential disputes. - -**2. Conversion Scenarios Modeling:** - -- **Scenario Analysis:** Model various conversion scenarios based on different company valuations and financing events to understand potential outcomes for both the investor and company. -- **Impact on Cap Table:** Analyze how different conversion scenarios will affect the company's equity distribution and the dilution of existing shareholders. - -**3. Rights and Preferences Evaluation:** - -- **Investor Protections:** Evaluate the effectiveness of the valuation cap, discount rate, and MFN provisions in protecting investor interests. -- **Future Round Implications:** Consider how these rights might influence future fundraising efforts and investor relations. - -**4. Standard vs. Non-standard Terms Identification:** - -- **Market Comparisons:** Compare the agreement's terms against industry standards to identify any non-standard provisions that may require negotiation or adjustment. -- **Risk Assessment:** Assess the risk associated with any non-standard terms, particularly in relation to future financing and investor relations. - -**5. Post-money vs. Pre-money SAFE Analysis:** - -- **Valuation Implications:** Understand the difference between post-money and pre-money SAFE agreements, as this affects the calculation of ownership percentages and dilution. -- **Recommendation:** Ensure clarity on whether the SAFE is structured as pre-money or post-money to accurately assess its impact on the cap table. - -**Recommendations for Negotiations:** - -- **Valuation Cap and Discount Rate:** Consider negotiating these terms to ensure they align with market conditions and provide adequate investor protection. -- **MFN Clause:** Engage legal counsel to review and potentially simplify the MFN provision to facilitate future financing rounds. -- **Pro-rata Rights:** Clearly define the exercise conditions to avoid future disputes and ensure alignment with company growth strategies. -- **Legal and Financial Review:** Engage specialists to review the agreement for enforceability and to model potential financial outcomes. **Detailed Analysis of Venture Capital Term Sheet** - -**1. Economic Terms Analysis:** - -- **Pre/Post-money Valuation:** - - **Pre-money Valuation:** The company's valuation before the investment is made. It's crucial for determining the price per share and the percentage of the company the investor will own post-investment. - - **Post-money Valuation:** The valuation after the investment is made, calculated as pre-money valuation plus the new investment amount. - - **Market Standard Comparison:** Typically, early-stage startups have lower pre-money valuations, ranging from $3M to $10M, depending on the sector and traction. - - **Founder Impact Analysis:** A higher pre-money valuation minimizes dilution for founders but might set a high bar for future rounds. - -- **Share Price Calculation:** - - Calculated by dividing the pre-money valuation by the total number of pre-investment shares. - - **Market Standard Comparison:** Ensure the share price aligns with industry norms for similar stage companies. - - **Founder Impact Analysis:** Affects the dilution founders face; higher share prices generally mean less dilution. - -- **Capitalization Analysis:** - - Involves understanding the fully diluted capitalization, including all shares, options, warrants, and convertible securities. - - **Founder Impact Analysis:** Critical for understanding potential dilution and control implications. - -- **Option Pool Sizing:** - - Typically set aside 10-20% of post-money shares for future employee grants. - - **Market Standard Comparison:** 15% is common for early-stage rounds. - - **Founder Impact Analysis:** Larger pools increase pre-money dilution for founders. - -**2. Control Provisions Review:** - -- **Board Composition:** - - Defines the number of seats and who appoints them. Investors often seek at least one seat. - - **Market Standard Comparison:** A 3-5 member board is common, with one investor seat. - - **Founder Impact Analysis:** More investor seats can reduce founder control. - -- **Voting Rights:** - - Typically, investors want voting rights proportional to their ownership. - - **Market Standard Comparison:** Standard practice is one vote per share. - - **Founder Impact Analysis:** High investor voting power can limit founder decision-making. - -- **Protective Provisions:** - - Rights that give investors veto power over key decisions (e.g., sale of the company, issuance of new shares). - - **Market Standard Comparison:** Common for significant matters. - - **Founder Impact Analysis:** Can constrain founder flexibility in strategic decisions. - -- **Information Rights:** - - Entail regular financial and operational updates. - - **Market Standard Comparison:** Quarterly reports are typical. - - **Founder Impact Analysis:** Ensures transparency but can increase administrative burden. - -**3. Investor Rights Assessment:** - -- **Pro-rata Rights:** - - Allow investors to maintain their ownership percentage in future rounds. - - **Market Standard Comparison:** Common for early-stage investors. - - **Founder Impact Analysis:** Can limit the amount of shares available for new investors. - -- **Anti-dilution Protection:** - - Protects investors from dilution in down rounds, with full ratchet or weighted average being common methods. - - **Market Standard Comparison:** Weighted average is more founder-friendly. - - **Founder Impact Analysis:** Full ratchet can lead to significant founder dilution. - -- **Registration Rights:** - - Rights to register shares for public sale. - - **Market Standard Comparison:** Demand and piggyback rights are standard. - - **Founder Impact Analysis:** Typically, no immediate impact but relevant for IPO considerations. - -- **Right of First Refusal:** - - Allows investors to purchase shares before they are sold to a third party. - - **Market Standard Comparison:** Common to protect investor ownership. - - **Founder Impact Analysis:** Can complicate secondary sales. - -**4. Governance Structures:** - -- **Market Standard Comparison:** Early-stage companies often have a simple governance structure with founders retaining significant control. -- **Founder Impact Analysis:** Complex structures can dilute founder control and complicate decision-making. - -**5. Exit and Liquidity Provisions:** - -- **Liquidation Preferences:** - - Determine the order and amount investors receive before common shareholders in a liquidity event. - - **Market Standard Comparison:** 1x non-participating is common. - - **Founder Impact Analysis:** Participating preferences can significantly reduce returns for common shareholders. - -- **Drag-along Rights:** - - Allow majority shareholders to force minority shareholders to sell their shares in an acquisition. - - **Market Standard Comparison:** Common to facilitate exits. - - **Founder Impact Analysis:** Ensures alignment but reduces minority shareholder control. - -**Recommendations for Negotiations:** - -- **Valuation and Option Pool:** Negotiate a valuation that reflects company potential and a reasonable option pool to minimize founder dilution. -- **Board Composition and Protective Provisions:** Balance investor oversight with founder control. -- **Anti-dilution and Liquidation Preferences:** Opt for weighted average anti-dilution and non-participating liquidation preferences to protect founder interests. -- **Legal and Financial Review:** Engage professionals to ensure terms align with strategic goals and industry standards. **Compliance Checklist** - -1. **Regulatory Compliance:** - - Ensure adherence to relevant securities regulations, such as the Securities Act of 1933 and the Securities Exchange Act of 1934. - - Confirm that disclosure requirements are met, including financial statements and material risks. - - Evaluate if the company qualifies as an investment company under the Investment Company Act of 1940. - - Verify compliance with blue sky laws in applicable states for the offer and sale of securities. - -2. **Documentation Review:** - - Check for accuracy in legal definitions used within the term sheet. - - Assess the enforceability of key provisions, such as protective provisions and anti-dilution rights. - - Identify jurisdiction concerns, ensuring governing law clauses align with strategic needs. - - Review amendment provisions to ensure they allow for necessary flexibility and protection. - -3. **Risk Assessment:** - - Analyze legal precedents related to similar term sheet provisions. - - Assess regulatory exposure, particularly concerning investor rights and control provisions. - - Evaluate enforcement mechanisms for protective provisions and dispute resolution clauses. - - Review dispute resolution provisions, ensuring they are comprehensive and efficient. - -**Risk Assessment Summary** - -- **Securities Law Compliance Risk:** Moderate risk if disclosure and registration requirements are not fully met. -- **Corporate Governance Risk:** High risk if board composition and protective provisions overly favor investors, potentially leading to founder disenfranchisement. -- **Regulatory Exposure:** Low to moderate, depending on the company's industry and geographical reach. -- **Dispute Resolution Risk:** Low if arbitration or mediation clauses are included and jurisdiction is favorable. - -**Required Disclosures List** - -- Financial statements and projections. -- Material risks associated with the business and the investment. -- Information on existing and potential legal proceedings. -- Details on capitalization, including option pool and convertible securities. - -**Recommended Legal Modifications** - -- Adjust board composition to ensure a balanced representation of founders and investors. -- Opt for a weighted average anti-dilution provision to protect founder interests. -- Specify a clear and favorable jurisdiction for dispute resolution. -- Consider simplifying governance structures to maintain founder control while providing necessary investor oversight. - -**Jurisdiction-Specific Concerns** - -- Ensure compliance with state-specific blue sky laws for the offer and sale of securities. -- Consider the implications of governing law clauses, particularly if the company operates in multiple jurisdictions. -- Review state-specific requirements for board composition and shareholder rights to ensure compliance. - -This comprehensive analysis ensures that the venture capital term sheet aligns with legal compliance requirements while balancing the interests of both founders and investors. **Market Positioning Summary** - -The current venture capital term sheet aligns moderately well with market standards, but there are areas where competitiveness can be improved. The terms reflect a balance between investor control and founder protection, with room for adjustments to enhance founder-friendliness without compromising investor interests. - -**Comparative Analysis** - -1. **Stage-Appropriate Terms:** - - The term sheet is suitable for early-stage investments, offering standard protective provisions and anti-dilution rights. - - Board composition and control rights are more aligned with later-stage investments, which could be adjusted for early-stage flexibility. - -2. **Industry-Standard Provisions:** - - The inclusion of a weighted average anti-dilution provision is consistent with industry standards. - - Protective provisions are standard but may need fine-tuning to prevent founder disenfranchisement. - -3. **Geographic Variations:** - - Compliance with blue sky laws and state-specific regulations is critical. The term sheet adequately addresses these concerns but should be reviewed for any recent changes in state laws. - -4. **Recent Trend Analysis:** - - There's a growing trend towards more founder-friendly terms, including increased control over board decisions and simplified governance structures. - -**Trend Implications** - -- **Emerging Terms and Conditions:** - - Increased focus on founder-friendly provisions, such as enhanced voting rights and simplified governance. - -- **Shifting Market Standards:** - - A trend towards balancing investor protection with founder autonomy is evident, with more emphasis on collaborative governance. - -- **Industry-Specific Adaptations:** - - Tech and biotech sectors are seeing more flexible terms to accommodate rapid innovation and scaling needs. - -- **Regional Variations:** - - U.S. markets are increasingly adopting terms that offer founders more control, especially in tech hubs like Silicon Valley. - -**Negotiation Leverage Points** - -- Emphasize the inclusion of industry-standard anti-dilution provisions as a protective measure for investors. -- Highlight the potential for improved founder control to attract high-quality entrepreneurial talent. -- Use geographic compliance as a selling point for investors concerned with regulatory exposure. - -**Recommended Modifications** - -1. **Board Composition:** - - Adjust to ensure a balanced representation of founders and investors, possibly introducing independent board members. - -2. **Anti-Dilution Provisions:** - - Maintain the weighted average provision but clarify terms to protect founder interests further. - -3. **Governance Structure:** - - Simplify governance to enhance founder control while maintaining necessary investor oversight. - -4. **Dispute Resolution:** - - Specify a clear and favorable jurisdiction for dispute resolution to minimize legal uncertainties. - -By implementing these modifications, the term sheet can better align with current market trends and improve its competitiveness in attracting both investors and founders. \ No newline at end of file diff --git a/new_features_examples/medical_analysis/rearrange_video_examples/term_sheet_swarm.py b/new_features_examples/medical_analysis/rearrange_video_examples/term_sheet_swarm.py deleted file mode 100644 index 4e1dd72a..00000000 --- a/new_features_examples/medical_analysis/rearrange_video_examples/term_sheet_swarm.py +++ /dev/null @@ -1,243 +0,0 @@ -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 - - Risk Factors - - Negotiation Points - - Recommended Actions - - Areas Requiring Specialist Review""", - model_name="gpt-4o", - max_loops=1, -) - -# SAFE Agreement Specialist -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 - - Risk assessment for non-standard terms - - Recommendations for negotiations""", - model_name="gpt-4o", - max_loops=1, -) - -# Term Sheet Analyst -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 - - Founder impact analysis - - Investor rights summary - - Governance implications""", - model_name="gpt-4o", - max_loops=1, -) - -# Legal Compliance Analyst -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 - - Required disclosures list - - Recommended legal modifications - - Jurisdiction-specific concerns""", - model_name="gpt-4o", - max_loops=1, -) - -# Market Comparison Analyst -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 - - Trend implications - - Negotiation leverage points - - Recommended modifications""", - model_name="gpt-4o", - max_loops=1, -) - -# Create agent list -agents = [ - lead_analyst, - safe_specialist, - term_sheet_analyst, - legal_analyst, - market_analyst, -] - -# Define analysis flow -flow = f"""{lead_analyst.agent_name} -> {safe_specialist.agent_name} -> {term_sheet_analyst.agent_name} -> {legal_analyst.agent_name} -> {market_analyst.agent_name}""" - -# Create the swarm system -vc_analysis_system = AgentRearrange( - name="VC-Document-Analysis-Swarm", - description="SAFE and Term Sheet document analysis and Q&A system", - agents=agents, - flow=flow, - max_loops=1, - output_type="all", -) -# Example usage -if __name__ == "__main__": - try: - # 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 - """ - - # Add timestamp to the analysis - analysis_request = f"Timestamp: {datetime.now()}\nDocument for Analysis: {document_text}" - - # Run the analysis - analysis = vc_analysis_system.run(analysis_request) - - # Create analysis report - create_file_in_folder( - "reports", "vc_document_analysis.md", analysis - ) - except Exception as e: - print(f"An error occurred: {e}") diff --git a/new_features_examples/microstructure.py b/new_features_examples/microstructure.py deleted file mode 100644 index c13d2e3f..00000000 --- a/new_features_examples/microstructure.py +++ /dev/null @@ -1,1074 +0,0 @@ -import os -import threading -import time -from collections import deque -from dataclasses import dataclass -from datetime import datetime -from queue import Queue -from typing import Any, Dict, List, Optional, Tuple - -import ccxt -import numpy as np -import pandas as pd -from dotenv import load_dotenv -from loguru import logger -from scipy import stats -from swarm_models import OpenAIChat - -from swarms import Agent - -logger.enable("") - - -@dataclass -class MarketSignal: - timestamp: datetime - signal_type: str - source: str - data: Dict[str, Any] - confidence: float - metadata: Dict[str, Any] - - -class MarketDataBuffer: - def __init__(self, max_size: int = 10000): - self.max_size = max_size - self.data = deque(maxlen=max_size) - self.lock = threading.Lock() - - def add(self, item: Any) -> None: - with self.lock: - self.data.append(item) - - def get_latest(self, n: int = None) -> List[Any]: - with self.lock: - if n is None: - return list(self.data) - return list(self.data)[-n:] - - -class SignalCSVWriter: - def __init__(self, output_dir: str = "market_data"): - self.output_dir = output_dir - self.ensure_output_dir() - self.files = {} - - def ensure_output_dir(self): - if not os.path.exists(self.output_dir): - os.makedirs(self.output_dir) - - def get_filename(self, signal_type: str, symbol: str) -> str: - date_str = datetime.now().strftime("%Y%m%d") - return ( - f"{self.output_dir}/{signal_type}_{symbol}_{date_str}.csv" - ) - - def write_order_book_signal(self, signal: MarketSignal): - symbol = signal.data["symbol"] - metrics = signal.data["metrics"] - filename = self.get_filename("order_book", symbol) - - # Create header if file doesn't exist - if not os.path.exists(filename): - header = [ - "timestamp", - "symbol", - "bid_volume", - "ask_volume", - "mid_price", - "bid_vwap", - "ask_vwap", - "spread", - "depth_imbalance", - "confidence", - ] - with open(filename, "w") as f: - f.write(",".join(header) + "\n") - - # Write data - data = [ - str(signal.timestamp), - symbol, - str(metrics["bid_volume"]), - str(metrics["ask_volume"]), - str(metrics["mid_price"]), - str(metrics["bid_vwap"]), - str(metrics["ask_vwap"]), - str(metrics["spread"]), - str(metrics["depth_imbalance"]), - str(signal.confidence), - ] - - with open(filename, "a") as f: - f.write(",".join(data) + "\n") - - def write_tick_signal(self, signal: MarketSignal): - symbol = signal.data["symbol"] - metrics = signal.data["metrics"] - filename = self.get_filename("tick_data", symbol) - - if not os.path.exists(filename): - header = [ - "timestamp", - "symbol", - "vwap", - "price_momentum", - "volume_mean", - "trade_intensity", - "kyle_lambda", - "roll_spread", - "confidence", - ] - with open(filename, "w") as f: - f.write(",".join(header) + "\n") - - data = [ - str(signal.timestamp), - symbol, - str(metrics["vwap"]), - str(metrics["price_momentum"]), - str(metrics["volume_mean"]), - str(metrics["trade_intensity"]), - str(metrics["kyle_lambda"]), - str(metrics["roll_spread"]), - str(signal.confidence), - ] - - with open(filename, "a") as f: - f.write(",".join(data) + "\n") - - def write_arbitrage_signal(self, signal: MarketSignal): - if ( - "best_opportunity" not in signal.data - or not signal.data["best_opportunity"] - ): - return - - symbol = signal.data["symbol"] - opp = signal.data["best_opportunity"] - filename = self.get_filename("arbitrage", symbol) - - if not os.path.exists(filename): - header = [ - "timestamp", - "symbol", - "buy_venue", - "sell_venue", - "spread", - "return", - "buy_price", - "sell_price", - "confidence", - ] - with open(filename, "w") as f: - f.write(",".join(header) + "\n") - - data = [ - str(signal.timestamp), - symbol, - opp["buy_venue"], - opp["sell_venue"], - str(opp["spread"]), - str(opp["return"]), - str(opp["buy_price"]), - str(opp["sell_price"]), - str(signal.confidence), - ] - - with open(filename, "a") as f: - f.write(",".join(data) + "\n") - - -class ExchangeManager: - def __init__(self): - self.available_exchanges = { - "kraken": ccxt.kraken, - "coinbase": ccxt.coinbase, - "kucoin": ccxt.kucoin, - "bitfinex": ccxt.bitfinex, - "gemini": ccxt.gemini, - } - self.active_exchanges = {} - self.test_exchanges() - - def test_exchanges(self): - """Test each exchange and keep only the accessible ones""" - for name, exchange_class in self.available_exchanges.items(): - try: - exchange = exchange_class() - exchange.load_markets() - self.active_exchanges[name] = exchange - logger.info(f"Successfully connected to {name}") - except Exception as e: - logger.warning(f"Could not connect to {name}: {e}") - - def get_primary_exchange(self) -> Optional[ccxt.Exchange]: - """Get the first available exchange""" - if not self.active_exchanges: - raise RuntimeError("No exchanges available") - return next(iter(self.active_exchanges.values())) - - def get_all_active_exchanges(self) -> Dict[str, ccxt.Exchange]: - """Get all active exchanges""" - return self.active_exchanges - - -class BaseMarketAgent(Agent): - def __init__( - self, - agent_name: str, - system_prompt: str, - api_key: str, - model_name: str = "gpt-4-0125-preview", - temperature: float = 0.1, - ): - model = OpenAIChat( - openai_api_key=api_key, - model_name=model_name, - temperature=temperature, - ) - super().__init__( - agent_name=agent_name, - system_prompt=system_prompt, - llm=model, - max_loops=1, - autosave=True, - dashboard=False, - verbose=True, - dynamic_temperature_enabled=True, - context_length=200000, - streaming_on=True, - output_type="str", - ) - self.signal_queue = Queue() - self.is_running = False - self.last_update = datetime.now() - self.update_interval = 1.0 # seconds - - def rate_limit_check(self) -> bool: - current_time = datetime.now() - if ( - current_time - self.last_update - ).total_seconds() < self.update_interval: - return False - self.last_update = current_time - return True - - -class OrderBookAgent(BaseMarketAgent): - def __init__(self, api_key: str): - system_prompt = """ - You are an Order Book Analysis Agent specialized in detecting institutional flows. - Monitor order book depth and changes to identify potential large trades and institutional activity. - Analyze patterns in order placement and cancellation rates. - """ - super().__init__("OrderBookAgent", system_prompt, api_key) - exchange_manager = ExchangeManager() - self.exchange = exchange_manager.get_primary_exchange() - self.order_book_buffer = MarketDataBuffer(max_size=100) - self.vwap_window = 20 - - def calculate_order_book_metrics( - self, order_book: Dict - ) -> Dict[str, float]: - bids = np.array(order_book["bids"]) - asks = np.array(order_book["asks"]) - - # Calculate key metrics - bid_volume = np.sum(bids[:, 1]) - ask_volume = np.sum(asks[:, 1]) - mid_price = (bids[0][0] + asks[0][0]) / 2 - - # Calculate VWAP - bid_vwap = ( - np.sum( - bids[: self.vwap_window, 0] - * bids[: self.vwap_window, 1] - ) - / bid_volume - if bid_volume > 0 - else 0 - ) - ask_vwap = ( - np.sum( - asks[: self.vwap_window, 0] - * asks[: self.vwap_window, 1] - ) - / ask_volume - if ask_volume > 0 - else 0 - ) - - # Calculate order book slope - bid_slope = np.polyfit( - range(len(bids[:10])), bids[:10, 0], 1 - )[0] - ask_slope = np.polyfit( - range(len(asks[:10])), asks[:10, 0], 1 - )[0] - - return { - "bid_volume": bid_volume, - "ask_volume": ask_volume, - "mid_price": mid_price, - "bid_vwap": bid_vwap, - "ask_vwap": ask_vwap, - "bid_slope": bid_slope, - "ask_slope": ask_slope, - "spread": asks[0][0] - bids[0][0], - "depth_imbalance": (bid_volume - ask_volume) - / (bid_volume + ask_volume), - } - - def detect_large_orders( - self, metrics: Dict[str, float], threshold: float = 2.0 - ) -> bool: - historical_books = self.order_book_buffer.get_latest(20) - if not historical_books: - return False - - # Calculate historical volume statistics - hist_volumes = [ - book["bid_volume"] + book["ask_volume"] - for book in historical_books - ] - volume_mean = np.mean(hist_volumes) - volume_std = np.std(hist_volumes) - - current_volume = metrics["bid_volume"] + metrics["ask_volume"] - z_score = (current_volume - volume_mean) / ( - volume_std if volume_std > 0 else 1 - ) - - return abs(z_score) > threshold - - def analyze_order_book(self, symbol: str) -> MarketSignal: - if not self.rate_limit_check(): - return None - - try: - order_book = self.exchange.fetch_order_book( - symbol, limit=100 - ) - metrics = self.calculate_order_book_metrics(order_book) - self.order_book_buffer.add(metrics) - - # Format data for LLM analysis - analysis_prompt = f""" - Analyze this order book for {symbol}: - Bid Volume: {metrics['bid_volume']} - Ask Volume: {metrics['ask_volume']} - 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? - """ - - # Get LLM analysis - llm_analysis = self.run(analysis_prompt) - - # Original signal creation with added LLM analysis - return MarketSignal( - timestamp=datetime.now(), - signal_type="order_book_analysis", - source="OrderBookAgent", - data={ - "metrics": metrics, - "large_order_detected": self.detect_large_orders( - metrics - ), - "symbol": symbol, - "llm_analysis": llm_analysis, # Add LLM insights - }, - confidence=min( - abs(metrics["depth_imbalance"]) * 0.7 - + ( - 1.0 - if self.detect_large_orders(metrics) - else 0.0 - ) - * 0.3, - 1.0, - ), - metadata={ - "update_latency": ( - datetime.now() - self.last_update - ).total_seconds(), - "buffer_size": len( - self.order_book_buffer.get_latest() - ), - }, - ) - except Exception as e: - logger.error(f"Error in order book analysis: {str(e)}") - return None - - -class TickDataAgent(BaseMarketAgent): - def __init__(self, api_key: str): - system_prompt = """ - You are a Tick Data Analysis Agent specialized in analyzing high-frequency price movements. - Monitor tick-by-tick data for patterns indicating short-term price direction. - Analyze trade size distribution and execution speed. - """ - super().__init__("TickDataAgent", system_prompt, api_key) - self.tick_buffer = MarketDataBuffer(max_size=5000) - 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: - price_changes = df["price"].diff().dropna() - volume_changes = df["volume"].diff().dropna() - - if len(price_changes) > 1 and len(volume_changes) > 1: - slope, _, _, _, _ = stats.linregress( - volume_changes, price_changes - ) - return abs(slope) - except Exception as e: - logger.warning(f"Error calculating Kyle's Lambda: {e}") - return 0.0 - - def calculate_roll_spread(self, df: pd.DataFrame) -> float: - """Calculate Roll's implied spread""" - try: - price_changes = df["price"].diff().dropna() - if len(price_changes) > 1: - autocov = np.cov( - price_changes[:-1], price_changes[1:] - )[0][1] - return 2 * np.sqrt(-autocov) if autocov < 0 else 0.0 - except Exception as e: - logger.warning(f"Error calculating Roll spread: {e}") - return 0.0 - - def calculate_tick_metrics( - self, ticks: List[Dict] - ) -> Dict[str, float]: - try: - # Debug the incoming data structure - logger.info( - f"Raw tick data structure: {ticks[0] if ticks else 'No ticks'}" - ) - - # Convert trades to proper format - formatted_trades = [] - for trade in ticks: - formatted_trade = { - "price": float( - trade.get("price", trade.get("last", 0)) - ), # Handle different exchange formats - "amount": float( - trade.get( - "amount", - trade.get( - "size", trade.get("quantity", 0) - ), - ) - ), - "timestamp": trade.get( - "timestamp", int(time.time() * 1000) - ), - } - formatted_trades.append(formatted_trade) - - df = pd.DataFrame(formatted_trades) - - if df.empty: - logger.warning("No valid trades to analyze") - return { - "vwap": 0.0, - "price_momentum": 0.0, - "volume_mean": 0.0, - "volume_std": 0.0, - "trade_intensity": 0.0, - "kyle_lambda": 0.0, - "roll_spread": 0.0, - } - - # Calculate metrics with the properly formatted data - metrics = {} - metrics["vwap"] = ( - (df["price"] * df["amount"]).sum() - / df["amount"].sum() - if not df.empty - else 0 - ) - metrics["price_momentum"] = ( - df["price"].diff().mean() if len(df) > 1 else 0 - ) - metrics["volume_mean"] = df["amount"].mean() - metrics["volume_std"] = df["amount"].std() - - time_diff = ( - (df["timestamp"].max() - df["timestamp"].min()) / 1000 - if len(df) > 1 - else 1 - ) - metrics["trade_intensity"] = ( - len(df) / time_diff if time_diff > 0 else 0 - ) - - metrics["kyle_lambda"] = self.calculate_kyle_lambda(df) - metrics["roll_spread"] = self.calculate_roll_spread(df) - - logger.info(f"Calculated metrics: {metrics}") - return metrics - - except Exception as e: - logger.error( - f"Error in calculate_tick_metrics: {str(e)}", - exc_info=True, - ) - # Return default metrics on error - return { - "vwap": 0.0, - "price_momentum": 0.0, - "volume_mean": 0.0, - "volume_std": 0.0, - "trade_intensity": 0.0, - "kyle_lambda": 0.0, - "roll_spread": 0.0, - } - - def analyze_ticks(self, symbol: str) -> MarketSignal: - if not self.rate_limit_check(): - return None - - try: - # Fetch recent trades - trades = self.exchange.fetch_trades(symbol, limit=100) - - # Debug the raw trades data - logger.info(f"Fetched {len(trades)} trades for {symbol}") - if trades: - logger.info(f"Sample trade: {trades[0]}") - - self.tick_buffer.add(trades) - recent_ticks = self.tick_buffer.get_latest(1000) - metrics = self.calculate_tick_metrics(recent_ticks) - - # Only proceed with LLM analysis if we have valid metrics - if metrics["vwap"] > 0: - analysis_prompt = f""" - Analyze these trading patterns for {symbol}: - VWAP: {metrics['vwap']:.2f} - 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 - 3. Trading activity patterns - """ - llm_analysis = self.run(analysis_prompt) - else: - llm_analysis = "Insufficient data for analysis" - - return MarketSignal( - timestamp=datetime.now(), - signal_type="tick_analysis", - source="TickDataAgent", - data={ - "metrics": metrics, - "symbol": symbol, - "prediction": np.sign(metrics["price_momentum"]), - "llm_analysis": llm_analysis, - }, - confidence=min(metrics["trade_intensity"] / 100, 1.0) - * 0.4 - + min(metrics["kyle_lambda"], 1.0) * 0.6, - metadata={ - "update_latency": ( - datetime.now() - self.last_update - ).total_seconds(), - "buffer_size": len(self.tick_buffer.get_latest()), - }, - ) - - except Exception as e: - logger.error( - f"Error in tick analysis: {str(e)}", exc_info=True - ) - return None - - -class LatencyArbitrageAgent(BaseMarketAgent): - def __init__(self, api_key: str): - system_prompt = """ - You are a Latency Arbitrage Agent specialized in detecting price discrepancies across venues. - Monitor multiple exchanges for price differences exceeding transaction costs. - Calculate optimal trade sizes and routes. - """ - super().__init__( - "LatencyArbitrageAgent", system_prompt, api_key - ) - exchange_manager = ExchangeManager() - self.exchanges = exchange_manager.get_all_active_exchanges() - self.fee_structure = { - "kraken": 0.0026, # 0.26% taker fee - "coinbase": 0.006, # 0.6% taker fee - "kucoin": 0.001, # 0.1% taker fee - "bitfinex": 0.002, # 0.2% taker fee - "gemini": 0.003, # 0.3% taker fee - } - self.price_buffer = { - ex: MarketDataBuffer(max_size=100) - for ex in self.exchanges - } - - def calculate_effective_prices( - self, ticker: Dict, venue: str - ) -> Tuple[float, float]: - """Calculate effective prices including fees""" - fee = self.fee_structure[venue] - return ( - ticker["bid"] * (1 - fee), # Effective sell price - ticker["ask"] * (1 + fee), # Effective buy price - ) - - def calculate_arbitrage_metrics( - self, prices: Dict[str, Dict] - ) -> Dict: - opportunities = [] - - for venue1 in prices: - for venue2 in prices: - if venue1 != venue2: - sell_price, _ = self.calculate_effective_prices( - prices[venue1], venue1 - ) - _, buy_price = self.calculate_effective_prices( - prices[venue2], venue2 - ) - - spread = sell_price - buy_price - if spread > 0: - opportunities.append( - { - "sell_venue": venue1, - "buy_venue": venue2, - "spread": spread, - "return": spread / buy_price, - "buy_price": buy_price, - "sell_price": sell_price, - } - ) - - return { - "opportunities": opportunities, - "best_opportunity": ( - max(opportunities, key=lambda x: x["return"]) - if opportunities - else None - ), - } - - def find_arbitrage(self, symbol: str) -> MarketSignal: - """ - Find arbitrage opportunities across exchanges with LLM analysis - """ - if not self.rate_limit_check(): - return None - - try: - prices = {} - timestamps = {} - - for name, exchange in self.exchanges.items(): - try: - ticker = exchange.fetch_ticker(symbol) - prices[name] = { - "bid": ticker["bid"], - "ask": ticker["ask"], - } - timestamps[name] = ticker["timestamp"] - self.price_buffer[name].add(prices[name]) - except Exception as e: - logger.warning( - f"Error fetching {name} price: {e}" - ) - - if len(prices) < 2: - return None - - metrics = self.calculate_arbitrage_metrics(prices) - - if not metrics["best_opportunity"]: - return None - - # Calculate confidence based on spread and timing - opp = metrics["best_opportunity"] - timing_factor = 1.0 - min( - abs( - timestamps[opp["sell_venue"]] - - timestamps[opp["buy_venue"]] - ) - / 1000, - 1.0, - ) - spread_factor = min( - opp["return"] * 5, 1.0 - ) # Scale return to confidence - - confidence = timing_factor * 0.4 + spread_factor * 0.6 - - # Format price data for LLM analysis - price_summary = "\n".join( - [ - f"{venue}: Bid ${prices[venue]['bid']:.2f}, Ask ${prices[venue]['ask']:.2f}" - for venue in prices.keys() - ] - ) - - # Create detailed analysis prompt - analysis_prompt = f""" - Analyze this arbitrage opportunity for {symbol}: - - Current Prices: - {price_summary} - - Best Opportunity Found: - Buy Venue: {opp['buy_venue']} at ${opp['buy_price']:.2f} - Sell Venue: {opp['sell_venue']} at ${opp['sell_price']:.2f} - Spread: ${opp['spread']:.2f} - Expected Return: {opp['return']*100:.3f}% - Time Difference: {abs(timestamps[opp['sell_venue']] - timestamps[opp['buy_venue']])}ms - - Consider: - 1. Is this opportunity likely to be profitable after execution costs? - 2. What risks might prevent successful execution? - 3. What market conditions might have created this opportunity? - 4. How does the timing difference affect execution probability? - """ - - # Get LLM analysis - llm_analysis = self.run(analysis_prompt) - - # Create comprehensive signal - return MarketSignal( - timestamp=datetime.now(), - signal_type="arbitrage_opportunity", - source="LatencyArbitrageAgent", - data={ - "metrics": metrics, - "symbol": symbol, - "best_opportunity": metrics["best_opportunity"], - "all_prices": prices, - "llm_analysis": llm_analysis, - "timing": { - "time_difference_ms": abs( - timestamps[opp["sell_venue"]] - - timestamps[opp["buy_venue"]] - ), - "timestamps": timestamps, - }, - }, - confidence=confidence, - metadata={ - "update_latency": ( - datetime.now() - self.last_update - ).total_seconds(), - "timestamp_deltas": timestamps, - "venue_count": len(prices), - "execution_risk": 1.0 - - timing_factor, # Higher time difference = higher risk - }, - ) - - except Exception as e: - logger.error(f"Error in arbitrage analysis: {str(e)}") - return None - - -class SwarmCoordinator: - def __init__(self, api_key: str): - self.api_key = api_key - self.agents = { - "order_book": OrderBookAgent(api_key), - "tick_data": TickDataAgent(api_key), - "latency_arb": LatencyArbitrageAgent(api_key), - } - self.signal_processors = [] - self.signal_history = MarketDataBuffer(max_size=1000) - self.running = False - self.lock = threading.Lock() - self.csv_writer = SignalCSVWriter() - - def register_signal_processor(self, processor): - """Register a new signal processor function""" - with self.lock: - self.signal_processors.append(processor) - - def process_signals(self, signals: List[MarketSignal]): - """Process signals through all registered processors""" - if not signals: - return - - self.signal_history.add(signals) - - try: - for processor in self.signal_processors: - processor(signals) - except Exception as e: - logger.error(f"Error in signal processing: {e}") - - def aggregate_signals( - self, signals: List[MarketSignal] - ) -> Dict[str, Any]: - """Aggregate multiple signals into a combined market view""" - if not signals: - return {} - - self.signal_history.add(signals) - - aggregated = { - "timestamp": datetime.now(), - "symbols": set(), - "agent_signals": {}, - "combined_confidence": 0, - "market_state": {}, - } - - for signal in signals: - symbol = signal.data.get("symbol") - if symbol: - aggregated["symbols"].add(symbol) - - agent_type = signal.source - if agent_type not in aggregated["agent_signals"]: - aggregated["agent_signals"][agent_type] = [] - aggregated["agent_signals"][agent_type].append(signal) - - # Update market state based on signal type - if signal.signal_type == "order_book_analysis": - metrics = signal.data.get("metrics", {}) - aggregated["market_state"].update( - { - "order_book_imbalance": metrics.get( - "depth_imbalance" - ), - "spread": metrics.get("spread"), - "large_orders_detected": signal.data.get( - "large_order_detected" - ), - } - ) - elif signal.signal_type == "tick_analysis": - metrics = signal.data.get("metrics", {}) - aggregated["market_state"].update( - { - "price_momentum": metrics.get( - "price_momentum" - ), - "trade_intensity": metrics.get( - "trade_intensity" - ), - "kyle_lambda": metrics.get("kyle_lambda"), - } - ) - elif signal.signal_type == "arbitrage_opportunity": - opp = signal.data.get("best_opportunity") - if opp: - aggregated["market_state"].update( - { - "arbitrage_spread": opp.get("spread"), - "arbitrage_return": opp.get("return"), - } - ) - - # Calculate combined confidence as weighted average - confidences = [s.confidence for s in signals] - if confidences: - aggregated["combined_confidence"] = np.mean(confidences) - - return aggregated - - def start(self, symbols: List[str], interval: float = 1.0): - """Start the swarm monitoring system""" - if self.running: - logger.warning("Swarm is already running") - return - - self.running = True - - def agent_loop(agent, symbol): - while self.running: - try: - if isinstance(agent, OrderBookAgent): - signal = agent.analyze_order_book(symbol) - elif isinstance(agent, TickDataAgent): - signal = agent.analyze_ticks(symbol) - elif isinstance(agent, LatencyArbitrageAgent): - signal = agent.find_arbitrage(symbol) - - if signal: - agent.signal_queue.put(signal) - except Exception as e: - logger.error( - f"Error in {agent.agent_name} loop: {e}" - ) - - time.sleep(interval) - - def signal_collection_loop(): - while self.running: - try: - current_signals = [] - - # Collect signals from all agents - for agent in self.agents.values(): - while not agent.signal_queue.empty(): - signal = agent.signal_queue.get_nowait() - if signal: - current_signals.append(signal) - - if current_signals: - # Process current signals - self.process_signals(current_signals) - - # Aggregate and analyze - aggregated = self.aggregate_signals( - current_signals - ) - logger.info( - f"Aggregated market view: {aggregated}" - ) - - except Exception as e: - logger.error( - f"Error in signal collection loop: {e}" - ) - - time.sleep(interval) - - # Start agent threads - self.threads = [] - for symbol in symbols: - for agent in self.agents.values(): - thread = threading.Thread( - target=agent_loop, - args=(agent, symbol), - daemon=True, - ) - thread.start() - self.threads.append(thread) - - # Start signal collection thread - collection_thread = threading.Thread( - target=signal_collection_loop, daemon=True - ) - collection_thread.start() - self.threads.append(collection_thread) - - def stop(self): - """Stop the swarm monitoring system""" - self.running = False - for thread in self.threads: - thread.join(timeout=5.0) - logger.info("Swarm stopped") - - -def market_making_processor(signals: List[MarketSignal]): - """Enhanced signal processor with LLM analysis integration""" - for signal in signals: - if signal.confidence > 0.8: - if signal.signal_type == "arbitrage_opportunity": - opp = signal.data.get("best_opportunity") - if ( - opp and opp["return"] > 0.001 - ): # 0.1% return threshold - logger.info( - "\nSignificant arbitrage opportunity detected:" - ) - logger.info(f"Return: {opp['return']*100:.3f}%") - logger.info(f"Spread: ${opp['spread']:.2f}") - if "llm_analysis" in signal.data: - logger.info("\nLLM Analysis:") - logger.info(signal.data["llm_analysis"]) - - elif signal.signal_type == "order_book_analysis": - imbalance = signal.data["metrics"]["depth_imbalance"] - if abs(imbalance) > 0.3: - logger.info( - f"\nSignificant order book imbalance detected: {imbalance:.3f}" - ) - if "llm_analysis" in signal.data: - logger.info("\nLLM Analysis:") - logger.info(signal.data["llm_analysis"]) - - elif signal.signal_type == "tick_analysis": - momentum = signal.data["metrics"]["price_momentum"] - if abs(momentum) > 0: - logger.info( - f"\nSignificant price momentum detected: {momentum:.3f}" - ) - if "llm_analysis" in signal.data: - logger.info("\nLLM Analysis:") - logger.info(signal.data["llm_analysis"]) - - -load_dotenv() -api_key = os.getenv("OPENAI_API_KEY") - -coordinator = SwarmCoordinator(api_key) -coordinator.register_signal_processor(market_making_processor) - -symbols = ["BTC/USDT", "ETH/USDT"] - -logger.info( - "Starting market microstructure analysis with LLM integration..." -) -logger.info(f"Monitoring symbols: {symbols}") -logger.info( - f"CSV files will be written to: {os.path.abspath('market_data')}" -) - -try: - coordinator.start(symbols) - while True: - time.sleep(1) -except KeyboardInterrupt: - logger.info("Gracefully shutting down...") - coordinator.stop() diff --git a/new_features_examples/multi_tool_usage_agent.py b/new_features_examples/multi_tool_usage_agent.py deleted file mode 100644 index 1af421e2..00000000 --- a/new_features_examples/multi_tool_usage_agent.py +++ /dev/null @@ -1,420 +0,0 @@ -import os -from typing import List, Dict, Any, Optional, Callable, get_type_hints -from dataclasses import dataclass, field -import json -from datetime import datetime -import inspect -import typing -from typing import Union -from swarms import Agent -from swarm_models import OpenAIChat - - -@dataclass -class ToolDefinition: - name: str - description: str - parameters: Dict[str, Any] - required_params: List[str] - callable: Optional[Callable] = None - - -def extract_type_hints(func: Callable) -> Dict[str, Any]: - """Extract parameter types from function type hints.""" - return typing.get_type_hints(func) - - -def extract_tool_info(func: Callable) -> ToolDefinition: - """Extract tool information from a callable function.""" - # Get function name - name = func.__name__ - - # Get docstring - description = inspect.getdoc(func) or "No description available" - - # Get parameters and their types - signature = inspect.signature(func) - type_hints = extract_type_hints(func) - - parameters = {} - required_params = [] - - for param_name, param in signature.parameters.items(): - # Skip self parameter for methods - if param_name == "self": - continue - - param_type = type_hints.get(param_name, Any) - - # Handle optional parameters - is_optional = ( - param.default != inspect.Parameter.empty - or getattr(param_type, "__origin__", None) is Union - and type(None) in param_type.__args__ - ) - - if not is_optional: - required_params.append(param_name) - - parameters[param_name] = { - "type": str(param_type), - "default": ( - None - if param.default is inspect.Parameter.empty - else param.default - ), - "required": not is_optional, - } - - return ToolDefinition( - name=name, - description=description, - parameters=parameters, - required_params=required_params, - callable=func, - ) - - -@dataclass -class FunctionSpec: - """Specification for a callable tool function.""" - - name: str - description: str - parameters: Dict[ - str, dict - ] # Contains type and description for each parameter - return_type: str - return_description: str - - -@dataclass -class ExecutionStep: - """Represents a single step in the execution plan.""" - - step_id: int - function_name: str - parameters: Dict[str, Any] - expected_output: str - completed: bool = False - result: Any = None - - -@dataclass -class ExecutionContext: - """Maintains state during execution.""" - - task: str - 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) - - -hints = get_type_hints(func) - - -class ToolAgent: - def __init__( - self, - functions: List[Callable], - openai_api_key: str, - model_name: str = "gpt-4", - temperature: float = 0.1, - ): - self.functions = {func.__name__: func for func in functions} - self.function_specs = self._analyze_functions(functions) - - self.model = OpenAIChat( - openai_api_key=openai_api_key, - model_name=model_name, - temperature=temperature, - ) - - self.system_prompt = self._create_system_prompt() - self.agent = Agent( - agent_name="Tool-Agent", - system_prompt=self.system_prompt, - llm=self.model, - max_loops=1, - verbose=True, - ) - - def _analyze_functions( - self, functions: List[Callable] - ) -> Dict[str, FunctionSpec]: - """Analyze functions to create detailed specifications.""" - specs = {} - for func in functions: - hints = get_type_hints(func) - sig = inspect.signature(func) - doc = inspect.getdoc(func) or "" - - # Parse docstring for parameter descriptions - param_descriptions = {} - current_param = None - for line in doc.split("\n"): - if ":param" in line: - param_name = ( - line.split(":param")[1].split(":")[0].strip() - ) - desc = line.split(":", 2)[-1].strip() - param_descriptions[param_name] = desc - elif ":return:" in line: - return_desc = line.split(":return:")[1].strip() - - # Build parameter specifications - parameters = {} - for name, param in sig.parameters.items(): - param_type = hints.get(name, Any) - parameters[name] = { - "type": str(param_type), - "type_class": param_type, - "description": param_descriptions.get(name, ""), - "required": param.default == param.empty, - } - - specs[func.__name__] = FunctionSpec( - name=func.__name__, - description=doc.split("\n")[0], - parameters=parameters, - return_type=str(hints.get("return", Any)), - return_description=( - return_desc if "return_desc" in locals() else "" - ), - ) - - return specs - - def _create_system_prompt(self) -> str: - """Create system prompt with detailed function specifications.""" - functions_desc = [] - for spec in self.function_specs.values(): - params_desc = [] - for name, details in spec.parameters.items(): - params_desc.append( - f" - {name}: {details['type']} - {details['description']}" - ) - - functions_desc.append( - f""" -Function: {spec.name} -Description: {spec.description} -Parameters: -{chr(10).join(params_desc)} -Returns: {spec.return_type} - {spec.return_description} - """ - ) - - return f"""You are an AI agent that creates and executes plans using available functions. - -Available Functions: -{chr(10).join(functions_desc)} - -You must respond in two formats depending on the phase: - -1. Planning Phase: -{{ - "phase": "planning", - "plan": {{ - "description": "Overall plan description", - "steps": [ - {{ - "step_id": 1, - "function": "function_name", - "parameters": {{ - "param1": "value1", - "param2": "value2" - }}, - "purpose": "Why this step is needed" - }} - ] - }} -}} - -2. Execution Phase: -{{ - "phase": "execution", - "analysis": "Analysis of current result", - "next_action": {{ - "type": "continue|request_input|complete", - "reason": "Why this action was chosen", - "needed_input": {{}} # If requesting input - }} -}} - -Always: -- Use exact function names -- Ensure parameter types match specifications -- Provide clear reasoning for each decision -""" - - def _execute_function( - self, spec: FunctionSpec, parameters: Dict[str, Any] - ) -> Any: - """Execute a function with type checking.""" - converted_params = {} - for name, value in parameters.items(): - param_spec = spec.parameters[name] - try: - # Convert value to required type - param_type = param_spec["type_class"] - if param_type in (int, float, str, bool): - converted_params[name] = param_type(value) - else: - converted_params[name] = value - except (ValueError, TypeError) as e: - raise ValueError( - f"Parameter '{name}' conversion failed: {str(e)}" - ) - - return self.functions[spec.name](**converted_params) - - def run(self, task: str) -> Dict[str, Any]: - """Execute task with planning and step-by-step execution.""" - context = ExecutionContext(task=task) - execution_log = { - "task": task, - "start_time": datetime.utcnow().isoformat(), - "steps": [], - "final_result": None, - } - - try: - # Planning phase - plan_prompt = f"Create a plan to: {task}" - plan_response = self.agent.run(plan_prompt) - plan_data = json.loads( - plan_response.replace("System:", "").strip() - ) - - # Convert plan to execution steps - for step in plan_data["plan"]["steps"]: - context.steps.append( - ExecutionStep( - step_id=step["step_id"], - function_name=step["function"], - parameters=step["parameters"], - expected_output=step["purpose"], - ) - ) - - # Execution phase - while context.current_step < len(context.steps): - step = context.steps[context.current_step] - print( - f"\nExecuting step {step.step_id}: {step.function_name}" - ) - - try: - # Execute function - spec = self.function_specs[step.function_name] - result = self._execute_function( - spec, step.parameters - ) - context.results[step.step_id] = result - step.completed = True - step.result = result - - # Get agent's analysis - analysis_prompt = f""" - Step {step.step_id} completed: - Function: {step.function_name} - Result: {json.dumps(result)} - Remaining steps: {len(context.steps) - context.current_step - 1} - - Analyze the result and decide next action. - """ - - analysis_response = self.agent.run( - analysis_prompt - ) - analysis_data = json.loads( - analysis_response.replace( - "System:", "" - ).strip() - ) - - execution_log["steps"].append( - { - "step_id": step.step_id, - "function": step.function_name, - "parameters": step.parameters, - "result": result, - "analysis": analysis_data, - } - ) - - if ( - analysis_data["next_action"]["type"] - == "complete" - ): - if ( - context.current_step - < len(context.steps) - 1 - ): - continue - break - - context.current_step += 1 - - except Exception as e: - print(f"Error in step {step.step_id}: {str(e)}") - execution_log["steps"].append( - { - "step_id": step.step_id, - "function": step.function_name, - "parameters": step.parameters, - "error": str(e), - } - ) - raise - - # Final analysis - final_prompt = f""" - Task completed. Results: - {json.dumps(context.results, indent=2)} - - Provide final analysis and recommendations. - """ - - final_analysis = self.agent.run(final_prompt) - execution_log["final_result"] = { - "success": True, - "results": context.results, - "analysis": json.loads( - final_analysis.replace("System:", "").strip() - ), - } - - except Exception as e: - execution_log["final_result"] = { - "success": False, - "error": str(e), - } - - execution_log["end_time"] = datetime.utcnow().isoformat() - return execution_log - - -def calculate_investment_return( - principal: float, rate: float, years: int -) -> float: - """Calculate investment return with compound interest. - - :param principal: Initial investment amount in dollars - :param rate: Annual interest rate as decimal (e.g., 0.07 for 7%) - :param years: Number of years to invest - :return: Final investment value - """ - return principal * (1 + rate) ** years - - -agent = ToolAgent( - functions=[calculate_investment_return], - openai_api_key=os.getenv("OPENAI_API_KEY"), -) - -result = agent.run( - "Calculate returns for $10000 invested at 7% for 10 years" -) diff --git a/new_features_examples/ollama_demo.py b/new_features_examples/ollama_demo.py deleted file mode 100644 index 4d1d41ef..00000000 --- a/new_features_examples/ollama_demo.py +++ /dev/null @@ -1,252 +0,0 @@ -""" -- 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 -- 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 -> -- how to manage diseases and by looking at correlating lab, docs, diagnoses -- 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, -> -- 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 - -model = OllamaModel(model_name="llama3.2") - -chief_medical_officer = Agent( - agent_name="Chief Medical Officer", - system_prompt="""You are the Chief Medical Officer coordinating a team of medical specialists for viral disease diagnosis. - Your responsibilities include: - - Gathering initial patient symptoms and medical history - - Coordinating with specialists to form differential diagnoses - - Synthesizing different specialist opinions into a cohesive diagnosis - - Ensuring all relevant symptoms and test results are considered - - Making final diagnostic recommendations - - 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, -) - -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 - * Suspected viral conditions - * Associated symptoms - * Complications - - 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, -) - -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 - * Secondary diagnoses - * Complications - * 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, -) - -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 - - Description - - Supporting documentation - 2. Secondary Diagnosis Codes - - Listed in order of clinical significance - 3. Symptom Codes - 4. Complication Codes - 5. Coding Notes""", - llm=model, - max_loops=1, -) - -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 - - Secondary diagnoses with ICD-10 - - Supporting evidence - 2. Coding Summary - - Complete code list with descriptions - - Code hierarchy and relationships - - Supporting documentation - 3. Recommendations - - 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, -) - -# Create agent list -agents = [ - chief_medical_officer, - virologist, - internist, - medical_coder, - synthesizer, -] - -# Define diagnostic flow -flow = f"""{chief_medical_officer.agent_name} -> {virologist.agent_name} -> {internist.agent_name} -> {medical_coder.agent_name} -> {synthesizer.agent_name}""" - -# Create the swarm system -diagnosis_system = AgentRearrange( - name="Medical-coding-diagnosis-swarm", - description="Comprehensive medical diagnosis and coding system", - agents=agents, - flow=flow, - max_loops=1, - output_type="all", -) - - -def generate_coding_report(diagnosis_output: str) -> str: - """ - Generate a structured medical coding report from the diagnosis output. - """ - timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") - - report = f"""# Medical Diagnosis and Coding Report - Generated: {timestamp} - - ## Clinical Summary - {diagnosis_output} - - ## Coding Summary - ### Primary Diagnosis Codes - [Extracted from synthesis] - - ### Secondary Diagnosis Codes - [Extracted from synthesis] - - ### Symptom Codes - [Extracted from synthesis] - - ### Procedure Codes (if applicable) - [Extracted from synthesis] - - ## Documentation and Compliance Notes - - Code justification - - Supporting documentation references - - Any coding queries or clarifications needed - - ## Recommendations - - Additional documentation needed - - Suggested follow-up - - Coding optimization opportunities - """ - return report - - -if __name__ == "__main__": - # Example patient case - patient_case = """ - Patient: 45-year-old White Male - - Lab Results: - - egfr - - 59 ml / min / 1.73 - - non african-american - - """ - - # Add timestamp to the patient case - case_info = f"Timestamp: {datetime.now()}\nPatient Information: {patient_case}" - - # Run the diagnostic process - diagnosis = diagnosis_system.run(case_info) - - # Generate coding report - coding_report = generate_coding_report(diagnosis) - - # Create reports - create_file_in_folder( - "reports", "medical_diagnosis_report.md", diagnosis - ) - create_file_in_folder( - "reports", "medical_coding_report.md", coding_report - ) diff --git a/new_features_examples/openai_assistant_wrapper.py b/new_features_examples/openai_assistant_wrapper.py deleted file mode 100644 index 2944ec11..00000000 --- a/new_features_examples/openai_assistant_wrapper.py +++ /dev/null @@ -1,14 +0,0 @@ -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 -) - -print( - agent.run( - "Create a table of super high growth opportunities for AI. I have $40k to invest in ETFs, index funds, and more. Please create a table in markdown.", - ) -) diff --git a/new_features_examples/persistent_legal_agent.py b/new_features_examples/persistent_legal_agent.py deleted file mode 100644 index 65e8d61a..00000000 --- a/new_features_examples/persistent_legal_agent.py +++ /dev/null @@ -1,113 +0,0 @@ -import os -from swarms import Agent -from swarm_models import OpenAIChat -from dotenv import load_dotenv - -# Custom system prompt for VC legal document generation -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 -2. Follow standard VC document structures -3. Flag areas that need attorney review -4. Request necessary information for document completion -5. Maintain consistency across related documents -6. Output only when document is complete and verified - -Remember: All output should be marked as 'DRAFT' and require professional legal review.""" - - -def create_vc_legal_agent(): - load_dotenv() - api_key = os.getenv("OPENAI_API_KEY") - - # Configure the model with appropriate parameters for legal work - # Get the OpenAI API key from the environment variable - api_key = os.getenv("GROQ_API_KEY") - - # Model - model = OpenAIChat( - openai_api_base="https://api.groq.com/openai/v1", - openai_api_key=api_key, - model_name="llama-3.1-70b-versatile", - temperature=0.1, - ) - - # Initialize the persistent agent - agent = Agent( - agent_name="VC-Legal-Document-Agent", - system_prompt=VC_LEGAL_AGENT_PROMPT, - llm=model, - max_loops="auto", # Allows multiple iterations until completion - stopping_token="", # Agent will continue until this token is output - autosave=True, - dashboard=True, # Enable dashboard for monitoring - verbose=True, - dynamic_temperature_enabled=False, # Disable for consistency in legal documents - saved_state_path="vc_legal_agent_state.json", - user_name="legal_corp", - retry_attempts=3, - context_length=200000, - return_step_meta=True, - output_type="string", - streaming_on=False, - ) - - return agent - - -def generate_legal_document(agent, document_type, parameters): - """ - Generate a legal document with multiple refinement iterations - - Args: - agent: The initialized VC legal agent - document_type: Type of document to generate (e.g., "term_sheet", "investment_agreement") - parameters: Dict containing necessary parameters for the document - - Returns: - str: The generated document content - """ - 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 when complete - - Include [REQUIRES LEGAL REVIEW] tags for sections needing attorney attention. - """ - - return agent.run(prompt) - - -# Example usage -if __name__ == "__main__": - # Initialize the agent - legal_agent = create_vc_legal_agent() - - # Example parameters for a term sheet - parameters = { - "company_name": "TechStartup Inc.", - "investment_amount": "$5,000,000", - "valuation": "$20,000,000", - "investor_rights": [ - "Board seat", - "Pro-rata rights", - "Information rights", - ], - "type_of_security": "Series A Preferred Stock", - } - - # Generate a term sheet - document = generate_legal_document( - legal_agent, "term_sheet", parameters - ) - - # Save the generated document - with open("generated_term_sheet_draft.md", "w") as f: - f.write(document) diff --git a/new_features_examples/privacy_building.py b/new_features_examples/privacy_building.py deleted file mode 100644 index 68d85e3e..00000000 --- a/new_features_examples/privacy_building.py +++ /dev/null @@ -1,263 +0,0 @@ -import os -from swarms import Agent, AgentRearrange -from swarm_models import OpenAIChat - -# Get the OpenAI API key from the environment variable -api_key = os.getenv("OPENAI_API_KEY") - -# Create an instance of the OpenAIChat class -model = OpenAIChat( - api_key=api_key, model_name="gpt-4o-mini", temperature=0.1 -) - -# Initialize the matchmaker agent (Director) -matchmaker_agent = Agent( - agent_name="MatchmakerAgent", - system_prompt=""" - - You are the MatchmakerAgent, the primary coordinator for managing user profiles and facilitating meaningful connections while maintaining strict privacy standards. - - - - - - Full names - - Contact information (phone, email, social media) - - Exact location/address - - Financial information - - Personal identification numbers - - Workplace specifics - - - - - First name only - - Age range (not exact birth date) - - General location (city/region only) - - Interests and hobbies - - Relationship goals - - General profession category - - - - - Profile_Management - - - Review and verify user profiles for authenticity - - Ensure all shared information adheres to privacy guidelines - - Flag any potential security concerns - - - Match_Coordination - - - Analyze compatibility factors between users - - Prioritize matches based on shared interests and goals - - Monitor interaction patterns for safety and satisfaction - - - Communication_Flow - - - Coordinate information exchange between ProfileAnalyzer and ConnectionFacilitator - - Ensure smooth transition of approved information - - Maintain audit trail of information sharing - - - - - Consent_First - Never share information without explicit user consent - - Safety_Priority - Prioritize user safety and privacy over match potential - - Transparency - Be clear about what information is being shared and why - - """, - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="matchmaker_agent.json", -) - -# Initialize worker 1: Profile Analyzer -profile_analyzer = Agent( - agent_name="ProfileAnalyzer", - system_prompt=""" - - You are the ProfileAnalyzer, responsible for deeply understanding user profiles and identifying meaningful compatibility factors while maintaining strict privacy protocols. - - - - - - - All sensitive information must be encrypted - - Access logs must be maintained - - Data retention policies must be followed - - - - - Use anonymized IDs for internal processing - - Apply privacy-preserving analysis techniques - - Implement data minimization principles - - - - - - - Shared interests alignment - - Relationship goal compatibility - - Value system overlap - - Lifestyle compatibility - - Communication style matching - - - - - Inconsistent information - - Suspicious behavior patterns - - Policy violations - - Safety concerns - - - - - - - - Generate compatibility scores - - Identify shared interests and potential conversation starters - - Flag potential concerns for review - - Provide reasoning for match recommendations - - - - - Apply progressive information disclosure rules - - Implement multi-stage verification for sensitive data sharing - - Maintain audit trails of information access - - - """, - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="profile_analyzer.json", -) - -# Initialize worker 2: Connection Facilitator -connection_facilitator = Agent( - agent_name="ConnectionFacilitator", - system_prompt=""" - - You are the ConnectionFacilitator, responsible for managing the interaction between matched users and ensuring smooth, safe, and meaningful communication. - - - - - - - Manage introduction messages - - Monitor response patterns - - Flag any concerning behavior - - - - - Track engagement levels - - Identify conversation quality indicators - - Provide conversation suggestions when appropriate - - - - - Monitor relationship progression - - Record user feedback - - Update matching algorithms based on successful connections - - - - - - - Screen for inappropriate content - - Block prohibited information sharing - - Monitor for harassment or abuse - - - - - Implement progressive contact information sharing - - Maintain anonymized communication channels - - Protect user identity until mutual consent - - - - - - - - User engagement rates - - Communication quality scores - - Safety incident reports - - User satisfaction ratings - - - - - Collect interaction data - - Analyze success patterns - - Implement refinements to matching criteria - - Update safety protocols as needed - - - """, - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="connection_facilitator.json", -) - -# 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 - who manages the development of connections. Together, you must ensure that: - - 1. User privacy is maintained at all times - 2. Information is shared progressively and with consent - 3. Safety protocols are strictly followed - 4. Meaningful connections are prioritized over quantity - 5. User experience remains positive and engaging -""" - -# Create a list of agents -agents = [matchmaker_agent, profile_analyzer, connection_facilitator] - -# Define the flow pattern for the swarm -flow = "MatchmakerAgent -> ProfileAnalyzer -> ConnectionFacilitator" - -# Using AgentRearrange class to manage the swarm -agent_system = AgentRearrange( - name="dating-swarm", - description="Privacy-focused dating platform agent system", - agents=agents, - flow=flow, - return_json=False, - output_type="final", - max_loops=1, -) - -# 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 - starters without revealing any restricted information. -""" - -# Run the swarm system with the task -output = agent_system.run(task) -print(output) diff --git a/new_features_examples/real_estate_agent.py b/new_features_examples/real_estate_agent.py deleted file mode 100644 index 92864209..00000000 --- a/new_features_examples/real_estate_agent.py +++ /dev/null @@ -1,319 +0,0 @@ -""" -Zoe - Real Estate Agent - -""" - -from typing import Optional, Dict, Any, List -from dataclasses import dataclass -from datetime import datetime -import os -import json -import requests -from loguru import logger -from swarms import Agent -from swarm_models import OpenAIChat -from dotenv import load_dotenv -from enum import Enum - -# Configure loguru logger -logger.add( - "logs/real_estate_agent_{time}.log", - rotation="500 MB", - retention="10 days", - level="INFO", - format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}", -) - - -class PropertyType(str, Enum): - """Enum for property types""" - - OFFICE = "office" - RETAIL = "retail" - INDUSTRIAL = "industrial" - MIXED_USE = "mixed-use" - LAND = "land" - - -@dataclass -class PropertyListing: - """Data class for commercial property listings""" - - property_id: str - address: str - city: str - state: str - zip_code: str - price: float - square_footage: float - property_type: PropertyType - zoning: str - listing_date: datetime - lat: float - lng: float - description: Optional[str] = None - features: Optional[List[str]] = None - images: Optional[List[str]] = None - - -class PropertyRadarAPI: - """Client for PropertyRadar API integration""" - - def __init__(self, api_key: str): - """Initialize PropertyRadar API client - - Args: - api_key (str): PropertyRadar API key - """ - self.api_key = api_key - self.base_url = "https://api.propertyradar.com/v1" - self.session = requests.Session() - self.session.headers.update( - { - "Authorization": f"Bearer {api_key}", - "Content-Type": "application/json", - } - ) - - def search_properties( - self, - max_price: float = 10_000_000, - property_types: List[PropertyType] = None, - location: Dict[str, Any] = None, - min_sqft: Optional[float] = None, - max_sqft: Optional[float] = None, - page: int = 1, - limit: int = 20, - ) -> List[PropertyListing]: - """ - Search for commercial properties using PropertyRadar API - - Args: - max_price (float): Maximum property price - property_types (List[PropertyType]): Types of properties to search for - location (Dict[str, Any]): Location criteria (city, county, or coordinates) - min_sqft (Optional[float]): Minimum square footage - max_sqft (Optional[float]): Maximum square footage - page (int): Page number for pagination - limit (int): Number of results per page - - Returns: - List[PropertyListing]: List of matching properties - """ - try: - # Build the query parameters - params = { - "price_max": max_price, - "property_types": ( - [pt.value for pt in property_types] - if property_types - else None - ), - "page": page, - "limit": limit, - "for_sale": True, - "state": "FL", # Florida only - "commercial_property": True, - } - - # Add location parameters - if location: - params.update(location) - - # Add square footage filters - if min_sqft: - params["square_feet_min"] = min_sqft - if max_sqft: - params["square_feet_max"] = max_sqft - - # Make the API request - response = self.session.get( - f"{self.base_url}/properties", - params={ - k: v for k, v in params.items() if v is not None - }, - ) - response.raise_for_status() - - # Parse the response - properties_data = response.json() - - # Convert to PropertyListing objects - return [ - PropertyListing( - property_id=prop["id"], - address=prop["address"], - city=prop["city"], - state=prop["state"], - zip_code=prop["zip_code"], - price=float(prop["price"]), - square_footage=float(prop["square_feet"]), - property_type=PropertyType(prop["property_type"]), - zoning=prop["zoning"], - listing_date=datetime.fromisoformat( - prop["list_date"] - ), - lat=float(prop["latitude"]), - lng=float(prop["longitude"]), - description=prop.get("description"), - features=prop.get("features", []), - images=prop.get("images", []), - ) - for prop in properties_data["results"] - ] - - except requests.RequestException as e: - logger.error(f"Error fetching properties: {str(e)}") - raise - - -class CommercialRealEstateAgent: - """Agent for searching and analyzing commercial real estate properties""" - - def __init__( - self, - openai_api_key: str, - propertyradar_api_key: str, - model_name: str = "gpt-4", - temperature: float = 0.1, - saved_state_path: Optional[str] = None, - ): - """Initialize the real estate agent - - Args: - openai_api_key (str): OpenAI API key - propertyradar_api_key (str): PropertyRadar API key - model_name (str): Name of the LLM model to use - temperature (float): Temperature setting for the LLM - saved_state_path (Optional[str]): Path to save agent state - """ - self.property_api = PropertyRadarAPI(propertyradar_api_key) - - # Initialize OpenAI model - self.model = OpenAIChat( - openai_api_key=openai_api_key, - model_name=model_name, - temperature=temperature, - ) - - # Initialize the agent - self.agent = Agent( - agent_name="Commercial-Real-Estate-Agent", - system_prompt=self._get_system_prompt(), - llm=self.model, - max_loops=1, - autosave=True, - dashboard=False, - verbose=True, - saved_state_path=saved_state_path, - context_length=200000, - streaming_on=False, - ) - - logger.info( - "Commercial Real Estate Agent initialized successfully" - ) - - def _get_system_prompt(self) -> str: - """Get the system prompt for the agent""" - return """You are a specialized commercial real estate agent assistant focused on Central Florida properties. - Your primary responsibilities are: - 1. Search for commercial properties under $10 million - 2. Focus on properties zoned for commercial use - 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 - - Traffic patterns and accessibility - - Nearby amenities and businesses - - Future development potential""" - - def search_properties( - self, - max_price: float = 10_000_000, - property_types: List[PropertyType] = None, - location: Dict[str, Any] = None, - min_sqft: Optional[float] = None, - max_sqft: Optional[float] = None, - ) -> List[Dict[str, Any]]: - """ - Search for properties and provide analysis - - Args: - max_price (float): Maximum property price - property_types (List[PropertyType]): Types of properties to search - location (Dict[str, Any]): Location criteria - min_sqft (Optional[float]): Minimum square footage - max_sqft (Optional[float]): Maximum square footage - - Returns: - List[Dict[str, Any]]: List of properties with analysis - """ - try: - # Search for properties - properties = self.property_api.search_properties( - max_price=max_price, - property_types=property_types, - location=location, - min_sqft=min_sqft, - max_sqft=max_sqft, - ) - - # Analyze each property - analyzed_properties = [] - for prop in properties: - analysis = self.agent.run( - f"Analyze this commercial property:\n" - f"Address: {prop.address}, {prop.city}, FL {prop.zip_code}\n" - f"Price: ${prop.price:,.2f}\n" - f"Square Footage: {prop.square_footage:,.0f}\n" - f"Property Type: {prop.property_type.value}\n" - f"Zoning: {prop.zoning}\n" - f"Description: {prop.description or 'Not provided'}" - ) - - analyzed_properties.append( - {"property": prop.__dict__, "analysis": analysis} - ) - - logger.info( - f"Successfully analyzed {len(analyzed_properties)} properties" - ) - return analyzed_properties - - except Exception as e: - logger.error( - f"Error in property search and analysis: {str(e)}" - ) - raise - - -def main(): - """Main function to demonstrate usage""" - load_dotenv() - - # Initialize the agent - agent = CommercialRealEstateAgent( - openai_api_key=os.getenv("OPENAI_API_KEY"), - propertyradar_api_key=os.getenv("PROPERTYRADAR_API_KEY"), - saved_state_path="real_estate_agent_state.json", - ) - - # Example search - results = agent.search_properties( - max_price=5_000_000, - property_types=[PropertyType.RETAIL, PropertyType.OFFICE], - location={"city": "Orlando", "radius_miles": 25}, - min_sqft=2000, - ) - - # Save results - with open("search_results.json", "w") as f: - json.dump(results, f, default=str, indent=2) - - -if __name__ == "__main__": - main() diff --git a/new_features_examples/rearrange_test.py b/new_features_examples/rearrange_test.py deleted file mode 100644 index d85e435a..00000000 --- a/new_features_examples/rearrange_test.py +++ /dev/null @@ -1,121 +0,0 @@ -import os - -from swarms import Agent, AgentRearrange - -from swarm_models import OpenAIChat - -# Get the OpenAI API key from the environment variable -api_key = os.getenv("OPENAI_API_KEY") - -# Create an instance of the OpenAIChat class -model = OpenAIChat( - api_key=api_key, model_name="gpt-4o-mini", temperature=0.1 -) - - -# Initialize the boss agent (Director) -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 - into a coherent report. - """, - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="boss_agent.json", -) - -# Initialize worker 1: Expense Analyzer -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. - Pay close attention to monthly recurring subscriptions, office supplies, and non-essential expenditures. - """, - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="worker1.json", -) - -# Initialize worker 2: Summary Generator -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 - 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. - """, - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="worker2.json", -) - -# Swarm-Level Prompt (Collaboration Prompt) -swarm_prompt = """ - As a swarm, your collective goal is to analyze the company's expenses and identify transactions that should be cut off. - You will work collaboratively to break down the entire process of expense analysis into manageable steps. - The BossAgent will direct the flow and assign tasks dynamically to the agents. The ExpenseAnalyzer will first - focus on breaking down the expense report, identifying high-cost recurring transactions, categorizing them, - and providing recommendations for potential cost reduction. After the analysis, the SummaryGenerator will then - consolidate all the findings into an actionable summary that the finance team can use to immediately cut off unnecessary expenses. - Together, your collaboration is essential to streamlining and improving the company’s financial health. -""" - -# Create a list of agents -agents = [boss_agent, worker1, worker2] - -# Define the flow pattern for the swarm -flow = "BossAgent -> ExpenseAnalyzer -> SummaryGenerator" - -# Using AgentRearrange class to manage the swarm -agent_system = AgentRearrange( - name="pe-swarm", - description="ss", - agents=agents, - flow=flow, - return_json=False, - output_type="final", - max_loops=1, - # docs=["SECURITY.md"], -) - -# Input task for the swarm -task = f""" - - {swarm_prompt} - - The company has been facing a rising number of unnecessary expenses, and the finance team needs a detailed - analysis of recent transactions to identify which expenses can be cut off to improve profitability. - Analyze the provided transaction data and create a detailed report on cost-cutting opportunities, - focusing on recurring transactions and non-essential expenditures. -""" - -# Run the swarm system with the task -output = agent_system.run(task) -print(output) diff --git a/new_features_examples/sequential_worflow_test.py b/new_features_examples/sequential_worflow_test.py deleted file mode 100644 index 8d204b39..00000000 --- a/new_features_examples/sequential_worflow_test.py +++ /dev/null @@ -1,118 +0,0 @@ -import os -from dotenv import load_dotenv -from swarms import Agent, SequentialWorkflow -from swarm_models import OpenAIChat - -load_dotenv() - -# Get the OpenAI API key from the environment variable -api_key = os.getenv("GROQ_API_KEY") - -# Model -model = OpenAIChat( - openai_api_base="https://api.groq.com/openai/v1", - openai_api_key=api_key, - model_name="llama-3.1-70b-versatile", - temperature=0.1, -) - - -# Initialize specialized agents -data_extractor_agent = Agent( - agent_name="Data-Extractor", - system_prompt=None, - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="data_extractor_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -summarizer_agent = Agent( - agent_name="Document-Summarizer", - system_prompt=None, - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="summarizer_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -financial_analyst_agent = Agent( - agent_name="Financial-Analyst", - system_prompt=None, - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="financial_analyst_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -market_analyst_agent = Agent( - agent_name="Market-Analyst", - system_prompt=None, - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="market_analyst_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -operational_analyst_agent = Agent( - agent_name="Operational-Analyst", - system_prompt=None, - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="operational_analyst_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -# Initialize the SwarmRouter -router = SequentialWorkflow( - name="pe-document-analysis-swarm", - description="Analyze documents for private equity due diligence and investment decision-making", - max_loops=1, - agents=[ - data_extractor_agent, - summarizer_agent, - financial_analyst_agent, - market_analyst_agent, - operational_analyst_agent, - ], - output_type="all", -) - -# Example usage -if __name__ == "__main__": - # Run a comprehensive private equity document analysis task - result = router.run( - "Where is the best place to find template term sheets for series A startups. Provide links and references", - img=None, - ) - print(result) diff --git a/new_features_examples/sequential_workflow.py b/new_features_examples/sequential_workflow.py deleted file mode 100644 index c688b088..00000000 --- a/new_features_examples/sequential_workflow.py +++ /dev/null @@ -1,143 +0,0 @@ -import os -from dotenv import load_dotenv -from swarms import Agent, SequentialWorkflow -from swarm_models import OpenAIChat - -load_dotenv() - -# Get the OpenAI API key from the environment variable -api_key = os.getenv("GROQ_API_KEY") - -# Model -model = OpenAIChat( - openai_api_base="https://api.groq.com/openai/v1", - openai_api_key=api_key, - model_name="llama-3.1-70b-versatile", - temperature=0.1, -) - - -# Initialize specialized agents -data_extractor_agent = Agent( - agent_name="Data-Extractor", - system_prompt="""You are a data extraction specialist. Your role is to: - 1. Extract key information, data points, and metrics from documents - 2. Identify and pull out important facts, figures, and statistics - 3. Structure extracted data in a clear, organized format - 4. Flag any inconsistencies or missing data - 5. Ensure accuracy in data extraction while maintaining context""", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="data_extractor_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -summarizer_agent = Agent( - agent_name="Document-Summarizer", - system_prompt="""You are a document summarization expert. Your role is to: - 1. Create concise, comprehensive summaries of documents - 2. Highlight key points and main takeaways - 3. Maintain the essential meaning while reducing length - 4. Structure summaries in a logical, readable format - 5. Identify and emphasize critical insights""", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="summarizer_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -financial_analyst_agent = Agent( - agent_name="Financial-Analyst", - system_prompt="""You are a financial analysis expert. Your role is to: - 1. Analyze financial statements and metrics - 2. Evaluate company valuations and financial projections - 3. Assess financial risks and opportunities - 4. Provide insights on financial performance and health - 5. Make recommendations based on financial analysis""", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="financial_analyst_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -market_analyst_agent = Agent( - agent_name="Market-Analyst", - system_prompt="""You are a market analysis expert. Your role is to: - 1. Analyze market trends and dynamics - 2. Evaluate competitive landscape and market positioning - 3. Identify market opportunities and threats - 4. Assess market size and growth potential - 5. Provide strategic market insights and recommendations""", - llm=model, - max_loops=1, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="market_analyst_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -operational_analyst_agent = Agent( - agent_name="Operational-Analyst", - system_prompt="""You are an operational analysis expert. Your role is to: - 1. Analyze business operations and processes - 2. Evaluate operational efficiency and effectiveness - 3. Identify operational risks and opportunities - 4. Assess scalability and growth potential - 5. Provide recommendations for operational improvements""", - llm=model, - max_loops=2, - autosave=True, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="operational_analyst_agent.json", - user_name="pe_firm", - retry_attempts=1, - context_length=200000, - output_type="string", -) - -# Initialize the SwarmRouter -router = SequentialWorkflow( - name="pe-document-analysis-swarm", - description="Analyze documents for private equity due diligence and investment decision-making", - max_loops=1, - agents=[ - data_extractor_agent, - summarizer_agent, - financial_analyst_agent, - market_analyst_agent, - operational_analyst_agent, - ], - output_type="all", -) - -# Example usage -if __name__ == "__main__": - # Run a comprehensive private equity document analysis task - result = router.run( - "Where is the best place to find template term sheets for series A startups. Provide links and references", - no_use_clusterops=True, - ) - print(result) diff --git a/new_features_examples/solana_agent.py b/new_features_examples/solana_agent.py deleted file mode 100644 index 28622f57..00000000 --- a/new_features_examples/solana_agent.py +++ /dev/null @@ -1,354 +0,0 @@ -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 decimal import Decimal - -# Swarms imports -from swarms import Agent - -# 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 - -# Specialized Solana Analysis System Prompt -SOLANA_ANALYSIS_PROMPT = """You are a specialized Solana blockchain analyst agent. Your role is to: - -1. Analyze real-time Solana transactions for patterns and anomalies -2. Identify potential market-moving transactions and whale movements -3. Detect important DeFi interactions across major protocols -4. Monitor program interactions for suspicious or notable activity -5. Track token movements across significant protocols like: - - Serum DEX - - Raydium - - Orca - - Marinade - - Jupiter - - Other major Solana protocols - -When analyzing transactions, consider: -- Transaction size relative to protocol norms -- Historical patterns for involved addresses -- Impact on protocol liquidity -- Relationship to known market events -- Potential wash trading or suspicious patterns -- MEV opportunities and arbitrage patterns -- Program interaction sequences - -Provide analysis in the following format: -{ - "analysis_type": "[whale_movement|program_interaction|defi_trade|suspicious_activity]", - "severity": "[high|medium|low]", - "details": { - "transaction_context": "...", - "market_impact": "...", - "recommended_actions": "...", - "related_patterns": "..." - } -} - -Focus on actionable insights that could affect: -1. Market movements -2. Protocol stability -3. Trading opportunities -4. Risk management -""" - - -@dataclass -class TransactionData: - """Data structure for parsed Solana transaction information""" - - signature: str - block_time: datetime - slot: int - fee: int - lamports: int - from_address: str - to_address: str - program_id: str - instruction_data: Optional[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]: - """Convert transaction data to dictionary for agent analysis""" - return { - "signature": self.signature, - "timestamp": self.block_time.isoformat(), - "slot": self.slot, - "fee": self.fee, - "amount_sol": str(self.sol_amount), - "from_address": self.from_address, - "to_address": self.to_address, - "program_id": self.program_id, - "instruction_data": self.instruction_data, - "program_logs": self.program_logs, - } - - -class SolanaSwarmAgent: - """Intelligent agent for analyzing Solana transactions using swarms""" - - def __init__( - self, - agent_name: str = "Solana-Analysis-Agent", - model_name: str = "gpt-4", - ): - self.agent = Agent( - agent_name=agent_name, - system_prompt=SOLANA_ANALYSIS_PROMPT, - model_name=model_name, - max_loops=1, - autosave=True, - dashboard=False, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="solana_agent.json", - user_name="solana_analyzer", - retry_attempts=3, - context_length=4000, - ) - - # Initialize known patterns database - self.known_patterns = { - "whale_addresses": set(), - "program_interactions": {}, - "recent_transactions": [], - } - logger.info( - f"Initialized {agent_name} with specialized Solana analysis capabilities" - ) - - async def analyze_transaction( - self, tx_data: TransactionData - ) -> Dict[str, Any]: - """Analyze a transaction using the specialized agent""" - try: - # Update recent transactions for pattern analysis - self.known_patterns["recent_transactions"].append( - tx_data.signature - ) - if len(self.known_patterns["recent_transactions"]) > 1000: - self.known_patterns["recent_transactions"].pop(0) - - # Prepare context for agent - context = { - "transaction": tx_data.to_dict(), - "known_patterns": { - "recent_similar_transactions": [ - tx - for tx in self.known_patterns[ - "recent_transactions" - ][-5:] - if abs( - TransactionData(tx).sol_amount - - tx_data.sol_amount - ) - < 1 - ], - "program_statistics": self.known_patterns[ - "program_interactions" - ].get(tx_data.program_id, {}), - }, - } - - # Get analysis from agent - analysis = await self.agent.run_async( - f"Analyze the following Solana transaction and provide insights: {json.dumps(context, indent=2)}" - ) - - # Update pattern database - if tx_data.sol_amount > 1000: # Track whale addresses - self.known_patterns["whale_addresses"].add( - tx_data.from_address - ) - - # Update program interaction statistics - if ( - tx_data.program_id - not in self.known_patterns["program_interactions"] - ): - self.known_patterns["program_interactions"][ - tx_data.program_id - ] = {"total_interactions": 0, "total_volume": 0} - self.known_patterns["program_interactions"][ - tx_data.program_id - ]["total_interactions"] += 1 - self.known_patterns["program_interactions"][ - tx_data.program_id - ]["total_volume"] += float(tx_data.sol_amount) - - return json.loads(analysis) - - except Exception as e: - logger.error(f"Error in agent analysis: {str(e)}") - return { - "analysis_type": "error", - "severity": "low", - "details": { - "error": str(e), - "transaction": tx_data.signature, - }, - } - - -class SolanaTransactionMonitor: - """Main class for monitoring and analyzing Solana transactions""" - - def __init__( - self, - rpc_url: str, - swarm_agent: SolanaSwarmAgent, - min_sol_threshold: Decimal = Decimal("100"), - ): - self.rpc_url = rpc_url - self.swarm_agent = swarm_agent - self.min_sol_threshold = min_sol_threshold - self.wallet = Wallet(Keypair()) - self.provider = Provider(rpc_url, self.wallet) - logger.info("Initialized Solana transaction monitor") - - async def parse_transaction( - self, tx_resp: GetTransactionResp - ) -> Optional[TransactionData]: - """Parse transaction response into TransactionData object""" - try: - if not tx_resp.value: - return None - - tx_value = tx_resp.value - meta = tx_value.transaction.meta - if not meta: - return None - - tx: Transaction = tx_value.transaction.transaction - - # Extract transaction details - from_pubkey = str(tx.message.account_keys[0]) - to_pubkey = str(tx.message.account_keys[1]) - program_id = str(tx.message.account_keys[-1]) - - # Calculate amount from balance changes - amount = abs(meta.post_balances[0] - meta.pre_balances[0]) - - return TransactionData( - signature=str(tx_value.transaction.signatures[0]), - block_time=datetime.fromtimestamp( - tx_value.block_time or 0 - ), - slot=tx_value.slot, - fee=meta.fee, - lamports=amount, - from_address=from_pubkey, - to_address=to_pubkey, - program_id=program_id, - program_logs=( - meta.log_messages if meta.log_messages else [] - ), - ) - except Exception as e: - logger.error(f"Failed to parse transaction: {str(e)}") - return None - - async def start_monitoring(self): - """Start monitoring for new transactions""" - logger.info( - "Starting transaction monitoring with swarm agent analysis" - ) - - async with aiohttp.ClientSession() as session: - async with session.ws_connect(self.rpc_url) as ws: - await ws.send_json( - { - "jsonrpc": "2.0", - "id": 1, - "method": "transactionSubscribe", - "params": [ - {"commitment": "finalized"}, - { - "encoding": "jsonParsed", - "commitment": "finalized", - }, - ], - } - ) - - async for msg in ws: - if msg.type == aiohttp.WSMsgType.TEXT: - try: - data = json.loads(msg.data) - if "params" in data: - signature = data["params"]["result"][ - "value" - ]["signature"] - - # Fetch full transaction data - tx_response = await self.provider.connection.get_transaction( - base58.b58decode(signature) - ) - - if tx_response: - tx_data = ( - await self.parse_transaction( - tx_response - ) - ) - if ( - tx_data - and tx_data.sol_amount - >= self.min_sol_threshold - ): - # Get agent analysis - analysis = await self.swarm_agent.analyze_transaction( - tx_data - ) - - logger.info( - f"Transaction Analysis:\n" - f"Signature: {tx_data.signature}\n" - f"Amount: {tx_data.sol_amount} SOL\n" - f"Analysis: {json.dumps(analysis, indent=2)}" - ) - - except Exception as e: - logger.error( - f"Error processing message: {str(e)}" - ) - continue - - -async def main(): - """Example usage""" - - # Start monitoring - try: - # Initialize swarm agent - swarm_agent = SolanaSwarmAgent( - agent_name="Solana-Whale-Detector", model_name="gpt-4" - ) - - # Initialize monitor - monitor = SolanaTransactionMonitor( - rpc_url="wss://api.mainnet-beta.solana.com", - swarm_agent=swarm_agent, - min_sol_threshold=Decimal("100"), - ) - - await monitor.start_monitoring() - except KeyboardInterrupt: - logger.info("Shutting down gracefully...") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/new_features_examples/spike/agent_rearrange_test.py b/new_features_examples/spike/agent_rearrange_test.py deleted file mode 100644 index e6aa044d..00000000 --- a/new_features_examples/spike/agent_rearrange_test.py +++ /dev/null @@ -1,238 +0,0 @@ -""" -Todo - -- You send structured data to the swarm through the users form they make -- then connect rag for every agent using llama index to remember all the students data -- structured outputs -""" - -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 - - -class CollegeLog(BaseModel): - college_name: str - college_description: str - college_admission_requirements: str - - -class CollegesRecommendation(BaseModel): - colleges: List[CollegeLog] - reasoning: str - - -load_dotenv() - -# Get the API key from environment variable -api_key = os.getenv("GROQ_API_KEY") - -# Initialize the model -model = OpenAIChat( - openai_api_base="https://api.groq.com/openai/v1", - openai_api_key=api_key, - model_name="llama-3.1-70b-versatile", - temperature=0.1, -) - -FINAL_AGENT_PROMPT = """ -You are a college selection final decision maker. Your role is to: - 1. Synthesize all previous analyses and discussions - 2. Weigh competing factors and trade-offs - 3. Create a final ranked list of recommended colleges - 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 - balance all relevant factors and stakeholder input. - -""" - -function_caller = OpenAIFunctionCaller( - system_prompt=FINAL_AGENT_PROMPT, - openai_api_key=os.getenv("OPENAI_API_KEY"), - base_model=CollegesRecommendation, - parallel_tool_calls=True, -) - -# Student Profile Analyzer Agent -profile_analyzer_agent = Agent( - agent_name="Student-Profile-Analyzer", - system_prompt="""You are an expert student profile analyzer. Your role is to: - 1. Analyze academic performance, test scores, and extracurricular activities - 2. Identify student's strengths, weaknesses, and unique qualities - 3. Evaluate personal statements and essays - 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 - (personal growth, challenges overcome, unique perspectives).""", - llm=model, - max_loops=1, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="profile_analyzer_agent.json", - user_name="student", - context_length=200000, - output_type="string", -) - -# College Research Agent -college_research_agent = Agent( - agent_name="College-Research-Specialist", - system_prompt="""You are a college research specialist. Your role is to: - 1. Maintain updated knowledge of college admission requirements - 2. Research academic programs, campus culture, and student life - 3. Analyze admission statistics and trends - 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, - max_loops=1, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="college_research_agent.json", - user_name="researcher", - context_length=200000, - output_type="string", -) - -# College Match Agent -college_match_agent = Agent( - agent_name="College-Match-Maker", - system_prompt="""You are a college matching specialist. Your role is to: - 1. Compare student profiles with college requirements - 2. Evaluate fit based on academic, social, and cultural factors - 3. Consider geographic preferences and constraints - 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 - considering both student preferences and admission probability.""", - llm=model, - max_loops=1, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="college_match_agent.json", - user_name="matcher", - context_length=200000, - output_type="string", -) - -# Debate Moderator Agent -debate_moderator_agent = Agent( - agent_name="Debate-Moderator", - system_prompt="""You are a college selection debate moderator. Your role is to: - 1. Facilitate discussions between different perspectives - 2. Ensure all relevant factors are considered - 3. Challenge assumptions and biases - 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, - max_loops=1, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="debate_moderator_agent.json", - user_name="moderator", - context_length=200000, - output_type="string", -) - -# Critique Agent -critique_agent = Agent( - agent_name="College-Selection-Critic", - system_prompt="""You are a college selection critic. Your role is to: - 1. Evaluate the strength of college matches - 2. Identify potential overlooked factors - 3. Challenge assumptions in the selection process - 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, - max_loops=1, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="critique_agent.json", - user_name="critic", - context_length=200000, - output_type="string", -) - -# Final Decision Agent -final_decision_agent = Agent( - agent_name="Final-Decision-Maker", - system_prompt=""" - You are a college selection final decision maker. Your role is to: - 1. Synthesize all previous analyses and discussions - 2. Weigh competing factors and trade-offs - 3. Create a final ranked list of recommended colleges - 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 - balance all relevant factors and stakeholder input. - """, - llm=model, - max_loops=1, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="final_decision_agent.json", - user_name="decision_maker", - context_length=200000, - output_type="string", -) - -# Initialize the Sequential Workflow -college_selection_workflow = AgentRearrange( - name="college-selection-swarm", - description="Comprehensive college selection and analysis system", - max_loops=1, - agents=[ - profile_analyzer_agent, - college_research_agent, - college_match_agent, - debate_moderator_agent, - critique_agent, - final_decision_agent, - ], - output_type="all", - flow=f"{profile_analyzer_agent.name} -> {college_research_agent.name} -> {college_match_agent.name} -> {debate_moderator_agent.name} -> {critique_agent.name} -> {final_decision_agent.name}", -) - -# Example usage -if __name__ == "__main__": - # Example student profile input - student_profile = """ - Student Profile: - - GPA: 3.8 - - SAT: 1450 - - Interests: Computer Science, Robotics - - Location Preference: East Coast - - Extracurriculars: Robotics Club President, Math Team - - Budget: Need financial aid - - Preferred Environment: Medium-sized urban campus - """ - - # Run the comprehensive college selection analysis - result = college_selection_workflow.run( - student_profile, - no_use_clusterops=True, - ) - print(result) diff --git a/new_features_examples/spike/function_caller_example.py b/new_features_examples/spike/function_caller_example.py deleted file mode 100644 index 0578df7d..00000000 --- a/new_features_examples/spike/function_caller_example.py +++ /dev/null @@ -1,64 +0,0 @@ -""" -Todo - -- You send structured data to the swarm through the users form they make -- then connect rag for every agent using llama index to remember all the students data -- structured outputs -""" - -import os -from dotenv import load_dotenv -from swarm_models import OpenAIChat, OpenAIFunctionCaller -from pydantic import BaseModel -from typing import List - - -class CollegeLog(BaseModel): - college_name: str - college_description: str - college_admission_requirements: str - - -class CollegesRecommendation(BaseModel): - colleges: List[CollegeLog] - reasoning: str - - -load_dotenv() - -# Get the API key from environment variable -api_key = os.getenv("GROQ_API_KEY") - -# Initialize the model -model = OpenAIChat( - openai_api_base="https://api.groq.com/openai/v1", - openai_api_key=api_key, - model_name="llama-3.1-70b-versatile", - temperature=0.1, -) - -function_caller = OpenAIFunctionCaller( - system_prompt="""You are a college selection final decision maker. Your role is to: - - Balance all relevant factors and stakeholder input. - - Only return the output in the schema format. - """, - openai_api_key=os.getenv("OPENAI_API_KEY"), - base_model=CollegesRecommendation, - # parallel_tool_calls=True, -) - - -print( - function_caller.run( - """ - Student Profile: Kye Gomez - - GPA: 3.8 - - SAT: 1450 - - Interests: Computer Science, Robotics - - Location Preference: East Coast - - Extracurriculars: Robotics Club President, Math Team - - Budget: Need financial aid - - Preferred Environment: Medium-sized urban campus - """ - ) -) diff --git a/new_features_examples/spike/memory.py b/new_features_examples/spike/memory.py deleted file mode 100644 index ce83aa7c..00000000 --- a/new_features_examples/spike/memory.py +++ /dev/null @@ -1,116 +0,0 @@ -from typing import Optional -from pathlib import Path -from loguru import logger -from llama_index.core import VectorStoreIndex, SimpleDirectoryReader - - -class LlamaIndexDB: - """A class to manage document indexing and querying using LlamaIndex. - - This class provides functionality to add documents from a directory and query the indexed documents. - - Args: - data_dir (str): Directory containing documents to index. Defaults to "docs". - **kwargs: Additional arguments passed to SimpleDirectoryReader and VectorStoreIndex. - SimpleDirectoryReader kwargs: - - filename_as_id (bool): Use filenames as document IDs - - recursive (bool): Recursively read subdirectories - - required_exts (List[str]): Only read files with these extensions - - exclude_hidden (bool): Skip hidden files - - VectorStoreIndex kwargs: - - service_context: Custom service context - - embed_model: Custom embedding model - - similarity_top_k (int): Number of similar docs to retrieve - - store_nodes_override (bool): Override node storage - """ - - def __init__(self, data_dir: str = "docs", **kwargs) -> None: - """Initialize the LlamaIndexDB with an empty index. - - Args: - data_dir (str): Directory containing documents to index - **kwargs: Additional arguments for SimpleDirectoryReader and VectorStoreIndex - """ - self.data_dir = data_dir - self.index: Optional[VectorStoreIndex] = None - self.reader_kwargs = { - k: v - for k, v in kwargs.items() - if k - in SimpleDirectoryReader.__init__.__code__.co_varnames - } - self.index_kwargs = { - k: v - for k, v in kwargs.items() - if k not in self.reader_kwargs - } - - logger.info("Initialized LlamaIndexDB") - data_path = Path(self.data_dir) - if not data_path.exists(): - logger.error(f"Directory not found: {self.data_dir}") - raise FileNotFoundError( - f"Directory {self.data_dir} does not exist" - ) - - try: - documents = SimpleDirectoryReader( - self.data_dir, **self.reader_kwargs - ).load_data() - self.index = VectorStoreIndex.from_documents( - documents, **self.index_kwargs - ) - logger.success( - f"Successfully indexed documents from {self.data_dir}" - ) - except Exception as e: - logger.error(f"Error indexing documents: {str(e)}") - raise - - def query(self, query: str, **kwargs) -> str: - """Query the indexed documents. - - Args: - query (str): The query string to search for - **kwargs: Additional arguments passed to the query engine - - similarity_top_k (int): Number of similar documents to retrieve - - streaming (bool): Enable streaming response - - response_mode (str): Response synthesis mode - - max_tokens (int): Maximum tokens in response - - Returns: - str: The response from the query engine - - Raises: - ValueError: If no documents have been indexed yet - """ - if self.index is None: - logger.error("No documents have been indexed yet") - raise ValueError("Must add documents before querying") - - try: - query_engine = self.index.as_query_engine(**kwargs) - response = query_engine.query(query) - print(response) - logger.info(f"Successfully queried: {query}") - return str(response) - except Exception as e: - logger.error(f"Error during query: {str(e)}") - raise - - -# # Example usage -# llama_index_db = LlamaIndexDB( -# data_dir="docs", -# filename_as_id=True, -# recursive=True, -# required_exts=[".txt", ".pdf", ".docx"], -# similarity_top_k=3 -# ) -# response = llama_index_db.query( -# "What is the medical history of patient 1?", -# streaming=True, -# response_mode="compact" -# ) -# print(response) diff --git a/new_features_examples/spike/spike.zip b/new_features_examples/spike/spike.zip deleted file mode 100644 index f817aaf2..00000000 Binary files a/new_features_examples/spike/spike.zip and /dev/null differ diff --git a/new_features_examples/spike/test.py b/new_features_examples/spike/test.py deleted file mode 100644 index 3c1f5fb5..00000000 --- a/new_features_examples/spike/test.py +++ /dev/null @@ -1,237 +0,0 @@ -""" -Todo - -- You send structured data to the swarm through the users form they make -- then connect rag for every agent using llama index to remember all the students data -- structured outputs -""" - -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 - - -class CollegeLog(BaseModel): - college_name: str - college_description: str - college_admission_requirements: str - - -class CollegesRecommendation(BaseModel): - colleges: List[CollegeLog] - reasoning: str - - -load_dotenv() - -# Get the API key from environment variable -api_key = os.getenv("GROQ_API_KEY") - -# Initialize the model -model = OpenAIChat( - openai_api_base="https://api.groq.com/openai/v1", - openai_api_key=api_key, - model_name="llama-3.1-70b-versatile", - temperature=0.1, -) - -FINAL_AGENT_PROMPT = """ -You are a college selection final decision maker. Your role is to: - 1. Synthesize all previous analyses and discussions - 2. Weigh competing factors and trade-offs - 3. Create a final ranked list of recommended colleges - 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 - balance all relevant factors and stakeholder input. - -""" - -function_caller = OpenAIFunctionCaller( - system_prompt=FINAL_AGENT_PROMPT, - openai_api_key=os.getenv("OPENAI_API_KEY"), - base_model=CollegesRecommendation, - parallel_tool_calls=True, -) - -# Student Profile Analyzer Agent -profile_analyzer_agent = Agent( - agent_name="Student-Profile-Analyzer", - system_prompt="""You are an expert student profile analyzer. Your role is to: - 1. Analyze academic performance, test scores, and extracurricular activities - 2. Identify student's strengths, weaknesses, and unique qualities - 3. Evaluate personal statements and essays - 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 - (personal growth, challenges overcome, unique perspectives).""", - llm=model, - max_loops=1, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="profile_analyzer_agent.json", - user_name="student", - context_length=200000, - output_type="string", -) - -# College Research Agent -college_research_agent = Agent( - agent_name="College-Research-Specialist", - system_prompt="""You are a college research specialist. Your role is to: - 1. Maintain updated knowledge of college admission requirements - 2. Research academic programs, campus culture, and student life - 3. Analyze admission statistics and trends - 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, - max_loops=1, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="college_research_agent.json", - user_name="researcher", - context_length=200000, - output_type="string", -) - -# College Match Agent -college_match_agent = Agent( - agent_name="College-Match-Maker", - system_prompt="""You are a college matching specialist. Your role is to: - 1. Compare student profiles with college requirements - 2. Evaluate fit based on academic, social, and cultural factors - 3. Consider geographic preferences and constraints - 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 - considering both student preferences and admission probability.""", - llm=model, - max_loops=1, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="college_match_agent.json", - user_name="matcher", - context_length=200000, - output_type="string", -) - -# Debate Moderator Agent -debate_moderator_agent = Agent( - agent_name="Debate-Moderator", - system_prompt="""You are a college selection debate moderator. Your role is to: - 1. Facilitate discussions between different perspectives - 2. Ensure all relevant factors are considered - 3. Challenge assumptions and biases - 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, - max_loops=1, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="debate_moderator_agent.json", - user_name="moderator", - context_length=200000, - output_type="string", -) - -# Critique Agent -critique_agent = Agent( - agent_name="College-Selection-Critic", - system_prompt="""You are a college selection critic. Your role is to: - 1. Evaluate the strength of college matches - 2. Identify potential overlooked factors - 3. Challenge assumptions in the selection process - 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, - max_loops=1, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="critique_agent.json", - user_name="critic", - context_length=200000, - output_type="string", -) - -# Final Decision Agent -final_decision_agent = Agent( - agent_name="Final-Decision-Maker", - system_prompt=""" - You are a college selection final decision maker. Your role is to: - 1. Synthesize all previous analyses and discussions - 2. Weigh competing factors and trade-offs - 3. Create a final ranked list of recommended colleges - 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 - balance all relevant factors and stakeholder input. - """, - llm=model, - max_loops=1, - verbose=True, - dynamic_temperature_enabled=True, - saved_state_path="final_decision_agent.json", - user_name="decision_maker", - context_length=200000, - output_type="string", -) - -# Initialize the Sequential Workflow -college_selection_workflow = SequentialWorkflow( - name="college-selection-swarm", - description="Comprehensive college selection and analysis system", - max_loops=1, - agents=[ - profile_analyzer_agent, - college_research_agent, - college_match_agent, - debate_moderator_agent, - critique_agent, - final_decision_agent, - ], - output_type="all", -) - -# Example usage -if __name__ == "__main__": - # Example student profile input - student_profile = """ - Student Profile: - - GPA: 3.8 - - SAT: 1450 - - Interests: Computer Science, Robotics - - Location Preference: East Coast - - Extracurriculars: Robotics Club President, Math Team - - Budget: Need financial aid - - Preferred Environment: Medium-sized urban campus - """ - - # Run the comprehensive college selection analysis - result = college_selection_workflow.run( - student_profile, - no_use_clusterops=True, - ) - print(result) diff --git a/new_features_examples/swarm_router_example.py b/new_features_examples/swarm_router_example.py deleted file mode 100644 index ef12a64e..00000000 --- a/new_features_examples/swarm_router_example.py +++ /dev/null @@ -1,164 +0,0 @@ -from swarms import Agent, SwarmRouter - -# Portfolio Analysis Specialist -portfolio_analyzer = Agent( - agent_name="Portfolio-Analysis-Specialist", - system_prompt="""You are an expert portfolio analyst specializing in fund analysis and selection. Your core competencies include: - - Comprehensive analysis of mutual funds, ETFs, and index funds - - Evaluation of fund performance metrics (expense ratios, tracking error, Sharpe ratio) - - 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 - 3. Assess historical performance and volatility - 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, - saved_state_path="portfolio_analyzer.json", - user_name="investment_team", - retry_attempts=2, - context_length=200000, - output_type="string", -) - -# Asset Allocation Strategist -allocation_strategist = Agent( - agent_name="Asset-Allocation-Strategist", - system_prompt="""You are a specialized asset allocation strategist focused on portfolio construction and optimization. Your expertise includes: - - Strategic and tactical asset allocation - - Risk tolerance assessment and portfolio matching - - 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 - 3. Select optimal fund combinations - 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, - saved_state_path="allocation_strategist.json", - user_name="investment_team", - retry_attempts=2, - context_length=200000, - output_type="string", -) - -# Risk Management Specialist -risk_manager = Agent( - agent_name="Risk-Management-Specialist", - system_prompt="""You are a risk management specialist focused on portfolio risk assessment and mitigation. Your expertise covers: - - Portfolio risk metrics analysis - - Downside protection strategies - - 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 - 3. Perform stress tests under various scenarios - 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, - saved_state_path="risk_manager.json", - user_name="investment_team", - retry_attempts=2, - context_length=200000, - output_type="string", -) - -# Portfolio Implementation Specialist -implementation_specialist = Agent( - agent_name="Portfolio-Implementation-Specialist", - system_prompt="""You are a portfolio implementation specialist focused on efficient execution and maintenance. Your responsibilities include: - - Fund selection for specific asset class exposure - - Tax-efficient implementation strategies - - 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 - 3. Design rebalancing schedule - 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, - saved_state_path="implementation_specialist.json", - user_name="investment_team", - retry_attempts=2, - context_length=200000, - output_type="string", -) - -# Portfolio Monitoring Specialist -monitoring_specialist = Agent( - agent_name="Portfolio-Monitoring-Specialist", - system_prompt="""You are a portfolio monitoring specialist focused on ongoing portfolio oversight and optimization. Your expertise includes: - - Regular portfolio performance review - - Drift monitoring and rebalancing triggers - - 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 - 3. Identify tax loss harvesting opportunities - 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, - saved_state_path="monitoring_specialist.json", - user_name="investment_team", - retry_attempts=2, - context_length=200000, - output_type="string", -) - -# List of all agents for portfolio management -portfolio_agents = [ - portfolio_analyzer, - allocation_strategist, - risk_manager, - implementation_specialist, - monitoring_specialist, -] - - -# Router -router = SwarmRouter( - name="etf-portfolio-management-swarm", - description="Creates and suggests an optimal portfolio", - agents=portfolio_agents, - swarm_type="SequentialWorkflow", # ConcurrentWorkflow - max_loops=1, -) - -router.run( - task="I have 10,000$ and I want to create a porfolio based on energy, ai, and datacenter companies. high growth." -) diff --git a/new_features_examples/swarms_claude_example.py b/new_features_examples/swarms_claude_example.py deleted file mode 100644 index 61da9f1e..00000000 --- a/new_features_examples/swarms_claude_example.py +++ /dev/null @@ -1,31 +0,0 @@ -from swarms import Agent -from swarms.prompts.finance_agent_sys_prompt import ( - FINANCIAL_AGENT_SYS_PROMPT, -) - -# Initialize the agent -agent = Agent( - agent_name="Financial-Analysis-Agent", - agent_description="Personal finance advisor agent", - system_prompt=FINANCIAL_AGENT_SYS_PROMPT - + "Output the token when you're done creating a portfolio of etfs, index, funds, and more for AI", - max_loops=1, - model_name="openai/gpt-4o", - dynamic_temperature_enabled=True, - user_name="Kye", - retry_attempts=3, - # streaming_on=True, - context_length=8192, - return_step_meta=False, - output_type="str", # "json", "dict", "csv" OR "string" "yaml" and - auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task - max_tokens=4000, # max output tokens - # interactive=True, - stopping_token="", - saved_state_path="agent_00.json", - interactive=False, -) - -agent.run( - "Create a table of super high growth opportunities for AI. I have $40k to invest in ETFs, index funds, and more. Please create a table in markdown.", -)