From 5a613e3df8d20168ec7c9e8dfa5eb8ad1bc2586d Mon Sep 17 00:00:00 2001 From: Occupying-Mars Date: Thu, 12 Dec 2024 02:19:55 +0530 Subject: [PATCH] readme fix --- README.md | 294 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 170 insertions(+), 124 deletions(-) diff --git a/README.md b/README.md index b4a6587b..a423d21d 100644 --- a/README.md +++ b/README.md @@ -453,8 +453,8 @@ agent.run(task, img) ---- -### `ToolAgent` -ToolAgent is an agent that can use tools through JSON function calling. It intakes any open source model from huggingface and is extremely modular and plug in and play. We need help adding general support to all models soon. +### Local Agent `ToolAgent` +ToolAgent is an fully local agent that can use tools through JSON function calling. It intakes any open source model from huggingface and is extremely modular and plug in and play. We need help adding general support to all models soon. ```python @@ -534,6 +534,7 @@ Swarm architectures leverage these communication patterns to ensure that agents | Hierarchical Swarms | A system where agents are organized in a hierarchy, with higher-level agents coordinating lower-level agents to achieve complex tasks. | [Code Link](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/#hierarchical-swarm) | Manufacturing process optimization, multi-level sales management, healthcare resource coordination | | Agent Rearrange | A setup where agents rearrange themselves dynamically based on the task requirements and environmental conditions. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/) | Adaptive manufacturing lines, dynamic sales territory realignment, flexible healthcare staffing | | Concurrent Workflows | Agents perform different tasks simultaneously, coordinating to complete a larger goal. | [Code Link](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/#concurrent-workflows) | Concurrent production lines, parallel sales operations, simultaneous patient care processes | +| AsyncWorkflow | Agents perform different tasks asynchronously, coordinating to complete a larger goal. | [Code Link](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/#async-workflow) | async production lines, parallel sales operations, simultaneous patient care processes | | Sequential Coordination | Agents perform tasks in a specific sequence, where the completion of one task triggers the start of the next. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/sequential_workflow/) | Step-by-step assembly lines, sequential sales processes, stepwise patient treatment workflows | | Parallel Processing | Agents work on different parts of a task simultaneously to speed up the overall process. | [Code Link](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/#parallel-processing) | Parallel data processing in manufacturing, simultaneous sales analytics, concurrent medical tests | | Mixture of Agents | A heterogeneous swarm where agents with different capabilities are combined to solve complex problems. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/moa/) | Financial forecasting, complex problem-solving requiring diverse skills | @@ -545,79 +546,6 @@ Swarm architectures leverage these communication patterns to ensure that agents | Swarm Router | Routes and chooses the swarm architecture based on the task requirements and available agents. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/) | Dynamic task routing, adaptive swarm architecture selection, optimized agent allocation | -### `AsyncWorkflow` - -## `AsyncWorkflow` -The `AsyncWorkflow` is designed for asynchronous task processing, allowing multiple agents to work concurrently on different tasks. This workflow is particularly useful for handling independent tasks that can be processed in parallel, improving overall execution efficiency. - -### Methods - -| Method | Description | Parameters | Return Value | -|--------|-------------|------------|--------------| -| `__init__` | Initialize the AsyncWorkflow | `name`: Name of the workflow
`agents`: List of Agent objects
`max_loops`: Maximum number of iterations | None | -| `run` | Execute the workflow asynchronously | `tasks`: List of tasks to process | List of task results | - -### Inputs - -| Input | Type | Description | -|-------|------|-------------| -| `name` | str | Name of the workflow | -| `agents` | List[Agent] | List of Agent objects to process tasks | -| `max_loops` | int | Maximum number of processing loops | -| `tasks` | List[str] | List of tasks to be processed | - -### Output - -The `run` method returns a list containing the results of all processed tasks. - -```python -import os -from swarms import Agent, AsyncWorkflow -from swarm_models import OpenAIChat - -# Initialize the model -model = OpenAIChat( - openai_api_key=os.getenv("OPENAI_API_KEY"), - model_name="gpt-4", - temperature=0.7 -) -# Initialize agents -agents = [ - Agent( - agent_name=f"Research-Agent-{i}", - system_prompt="You are a research agent specialized in gathering and analyzing information.", - llm=model, - max_loops=1, - verbose=True - ) - for i in range(3) -] -# Create tasks -research_tasks = [ - "Research the latest developments in quantum computing", - "Analyze the impact of AI on healthcare", - "Investigate renewable energy trends" -] -# Initialize AsyncWorkflow -workflow = AsyncWorkflow( -name="Research-Workflow", -agents=agents, -max_loops=1 -) -# Run tasks asynchronously -results = workflow.run(tasks=research_tasks) -# Process results -for task, result in zip(research_tasks, results): -print(f"\nTask: {task}") -print(f"Result: {result}") -``` - -The AsyncWorkflow is particularly useful when you need to: -- Process multiple independent tasks simultaneously -- Maximize resource utilization across multiple agents -- Reduce overall processing time for batch tasks -- Handle tasks with varying completion times efficiently - ### `SequentialWorkflow` Sequential Workflow enables you to sequentially execute tasks with `Agent` and then pass the output into the next agent and onwards until you have specified your max loops. @@ -847,6 +775,8 @@ print( The `AgentRearrange` orchestration technique, inspired by Einops and einsum, allows you to define and map out the relationships between various agents. It provides a powerful tool for orchestrating complex workflows, enabling you to specify linear and sequential relationships such as `a -> a1 -> a2 -> a3`, or concurrent relationships where the first agent sends a message to 3 agents simultaneously: `a -> a1, a2, a3`. This level of customization allows for the creation of highly efficient and dynamic workflows, where agents can work in parallel or in sequence as needed. The `AgentRearrange` technique is a valuable addition to the swarms library, providing a new level of flexibility and control over the orchestration of agents. For more detailed information and examples, please refer to the [official documentation](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/). +[Check out my video on agent rearrange!](https://youtu.be/Rq8wWQ073mg) + ### Methods @@ -872,68 +802,184 @@ The `run` method returns the final output after all agents have processed the in ```python -from swarms import Agent, AgentRearrange - +from datetime import datetime -# Initialize the director agent +from swarms import Agent, AgentRearrange, create_file_in_folder -director = Agent( - agent_name="Director", - system_prompt="Directs the tasks for the workers", - model_name="claude-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 + + 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, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="director.json", ) +# 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, +) -# Initialize worker 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, +) -worker1 = Agent( - agent_name="Worker1", - system_prompt="Generates a transcript for a youtube video on what swarms are", - model_name="claude-2", +# 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, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="worker1.json", ) +# Create agent list +agents = [chief_medical_officer, virologist, internist, synthesizer] -# Initialize worker 2 -worker2 = Agent( - agent_name="Worker2", - system_prompt="Summarizes the transcript generated by Worker1", - model_name="claude-2", +# 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, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="worker2.json", + output_type="all", ) -# Create a list of agents -agents = [director, worker1, worker2] +# 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 + """ -# Define the flow pattern -flow = "Director -> Worker1 -> Worker2" + # 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 + ) -# Using AgentRearrange class -agent_system = AgentRearrange(agents=agents, flow=flow) -output = agent_system.run( - "Create a format to express and communicate swarms of llms in a structured manner for youtube" -) -print(output) ``` @@ -1535,7 +1581,7 @@ print(output) ## `SwarmRouter` -The `SwarmRouter` class is a flexible routing system designed to manage different types of swarms for task execution. It provides a unified interface to interact with various swarm types, including `AgentRearrange`, `MixtureOfAgents`, `SpreadSheetSwarm`, `SequentialWorkflow`, and `ConcurrentWorkflow`. We will be continuously adding more and more swarm architectures here as we progress with new architectures. +The `SwarmRouter` class is a flexible routing system designed to manage different types of swarms for task execution. It provides a unified interface to interact with various swarm types, including `AgentRearrange`, `MixtureOfAgents`, `SpreadSheetSwarm`, `SequentialWorkflow`, and `ConcurrentWorkflow`, and `AsyncWorkflow`. We will be continuously adding more and more swarm architectures here as we progrFess with new architectures. #### Attributes: - `name` (str): Name of the SwarmRouter instance. @@ -1543,7 +1589,7 @@ The `SwarmRouter` class is a flexible routing system designed to manage differen - `max_loops` (int): Maximum number of loops to perform. - `agents` (List[Agent]): List of Agent objects to be used in the swarm. - `swarm_type` (SwarmType): Type of swarm to be used. -- `swarm` (Union[AgentRearrange, MixtureOfAgents, SpreadSheetSwarm, SequentialWorkflow, ConcurrentWorkflow]): Instantiated swarm object. +- `swarm` (Union[AgentRearrange, MixtureOfAgents, SpreadSheetSwarm, SequentialWorkflow, ConcurrentWorkflow, AsyncWorkflow]): Instantiated swarm object. - `logs` (List[SwarmLog]): List of log entries captured during operations. #### Methods: @@ -1702,7 +1748,7 @@ router = SwarmRouter( market_analyst_agent, operational_analyst_agent, ], - swarm_type="ConcurrentWorkflow", # or "SequentialWorkflow" or "ConcurrentWorkflow" or + swarm_type="ConcurrentWorkflow", # or "SequentialWorkflow" or "ConcurrentWorkflow" or "AsyncWorkflow" ) # Example usage @@ -1858,4 +1904,4 @@ Join our growing community around the world, for real-time support, ideas, and d # License -GNU AFFERO GENERAL PUBLIC LICENSE +GNU AFFERO GENERAL PUBLIC LICENSE \ No newline at end of file