commit
440bc288bf
@ -0,0 +1,387 @@
|
|||||||
|
|
||||||
|
# Welcome to Swarms Docs Home
|
||||||
|
|
||||||
|
[](https://discord.gg/jM3Z6M9uMq) [](https://www.youtube.com/@kyegomez3242) [](https://www.linkedin.com/in/kye-g-38759a207/) [](https://x.com/swarms_corp)
|
||||||
|
|
||||||
|
## What is Swarms?
|
||||||
|
|
||||||
|
**Swarms** is the **first and most reliable multi-agent production-grade framework** designed to orchestrate intelligent AI agents at scale. Built for enterprise applications, Swarms enables you to create sophisticated multi-agent systems that can handle complex tasks through collaboration, parallel processing, and intelligent task distribution.
|
||||||
|
|
||||||
|
### Key Capabilities
|
||||||
|
|
||||||
|
- **🏢 Production-Ready**: Enterprise-grade infrastructure with high reliability, comprehensive logging, and robust error handling
|
||||||
|
- **🤖 Multi-Agent Orchestration**: Support for hierarchical swarms, parallel processing, sequential workflows, and dynamic agent rearrangement
|
||||||
|
- **🔄 Flexible Integration**: Multi-model support, custom agent creation, extensive tool library, and multiple memory systems
|
||||||
|
- **📈 Scalable Architecture**: Concurrent processing, resource management, load balancing, and horizontal scaling capabilities
|
||||||
|
- **🛠️ Developer-Friendly**: Simple API, extensive documentation, active community, and CLI tools for rapid development
|
||||||
|
- **🔐 Enterprise Security**: Built-in error handling, rate limiting, monitoring integration, and audit logging
|
||||||
|
|
||||||
|
### Why Choose Swarms?
|
||||||
|
|
||||||
|
Swarms stands out as the **most reliable multi-agent framework** because it was built from the ground up for production environments. Unlike other frameworks that focus on research or simple demos, Swarms provides the infrastructure, tooling, and best practices needed to deploy multi-agent systems in real-world applications.
|
||||||
|
|
||||||
|
Whether you're building financial analysis systems, healthcare diagnostics, manufacturing optimization, or any other complex multi-agent application, Swarms provides the foundation you need to succeed.
|
||||||
|
|
||||||
|
Get started learning swarms with the following examples and more.
|
||||||
|
|
||||||
|
## Install 💻
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ pip3 install -U swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
### Using uv (Recommended)
|
||||||
|
[uv](https://github.com/astral-sh/uv) is a fast Python package installer and resolver, written in Rust.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Install uv
|
||||||
|
$ curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||||
|
|
||||||
|
# Install swarms using uv
|
||||||
|
$ uv pip install swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
### Using poetry
|
||||||
|
```bash
|
||||||
|
# Install poetry if you haven't already
|
||||||
|
$ curl -sSL https://install.python-poetry.org | python3 -
|
||||||
|
|
||||||
|
# Add swarms to your project
|
||||||
|
$ poetry add swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
### From source
|
||||||
|
```bash
|
||||||
|
# Clone the repository
|
||||||
|
$ git clone https://github.com/kyegomez/swarms.git
|
||||||
|
$ cd swarms
|
||||||
|
|
||||||
|
# Install with pip
|
||||||
|
$ pip install -e .
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Environment Configuration
|
||||||
|
|
||||||
|
[Learn more about the environment configuration here](https://docs.swarms.world/en/latest/swarms/install/env/)
|
||||||
|
|
||||||
|
```
|
||||||
|
OPENAI_API_KEY=""
|
||||||
|
WORKSPACE_DIR="agent_workspace"
|
||||||
|
ANTHROPIC_API_KEY=""
|
||||||
|
GROQ_API_KEY=""
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### 🤖 Your First Agent
|
||||||
|
|
||||||
|
An **Agent** is the fundamental building block of a swarm—an autonomous entity powered by an LLM + Tools + Memory. [Learn more Here](https://docs.swarms.world/en/latest/swarms/structs/agent/)
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Initialize a new agent
|
||||||
|
agent = Agent(
|
||||||
|
model_name="gpt-4o-mini", # Specify the LLM
|
||||||
|
max_loops=1, # Set the number of interactions
|
||||||
|
interactive=True, # Enable interactive mode for real-time feedback
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the agent with a task
|
||||||
|
agent.run("What are the key benefits of using a multi-agent system?")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🤝 Your First Swarm: Multi-Agent Collaboration
|
||||||
|
|
||||||
|
A **Swarm** consists of multiple agents working together. This simple example creates a two-agent workflow for researching and writing a blog post. [Learn More About SequentialWorkflow](https://docs.swarms.world/en/latest/swarms/structs/sequential_workflow/)
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, SequentialWorkflow
|
||||||
|
|
||||||
|
# Agent 1: The Researcher
|
||||||
|
researcher = Agent(
|
||||||
|
agent_name="Researcher",
|
||||||
|
system_prompt="Your job is to research the provided topic and provide a detailed summary.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Agent 2: The Writer
|
||||||
|
writer = Agent(
|
||||||
|
agent_name="Writer",
|
||||||
|
system_prompt="Your job is to take the research summary and write a beautiful, engaging blog post about it.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create a sequential workflow where the researcher's output feeds into the writer's input
|
||||||
|
workflow = SequentialWorkflow(agents=[researcher, writer])
|
||||||
|
|
||||||
|
# Run the workflow on a task
|
||||||
|
final_post = workflow.run("The history and future of artificial intelligence")
|
||||||
|
print(final_post)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
|
## 🏗️ Multi-Agent Architectures For Production Deployments
|
||||||
|
|
||||||
|
`swarms` provides a variety of powerful, pre-built multi-agent architectures enabling you to orchestrate agents in various ways. Choose the right structure for your specific problem to build efficient and reliable production systems.
|
||||||
|
|
||||||
|
| **Architecture** | **Description** | **Best For** |
|
||||||
|
|---|---|---|
|
||||||
|
| **[SequentialWorkflow](https://docs.swarms.world/en/latest/swarms/structs/sequential_workflow/)** | Agents execute tasks in a linear chain; one agent's output is the next one's input. | Step-by-step processes like data transformation pipelines, report generation. |
|
||||||
|
| **[ConcurrentWorkflow](https://docs.swarms.world/en/latest/swarms/structs/concurrent_workflow/)** | Agents run tasks simultaneously for maximum efficiency. | High-throughput tasks like batch processing, parallel data analysis. |
|
||||||
|
| **[AgentRearrange](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/)** | Dynamically maps complex relationships (e.g., `a -> b, c`) between agents. | Flexible and adaptive workflows, task distribution, dynamic routing. |
|
||||||
|
| **[GraphWorkflow](https://docs.swarms.world/en/latest/swarms/structs/graph_workflow/)** | Orchestrates agents as nodes in a Directed Acyclic Graph (DAG). | Complex projects with intricate dependencies, like software builds. |
|
||||||
|
| **[MixtureOfAgents (MoA)](https://docs.swarms.world/en/latest/swarms/structs/moa/)** | Utilizes multiple expert agents in parallel and synthesizes their outputs. | Complex problem-solving, achieving state-of-the-art performance through collaboration. |
|
||||||
|
| **[GroupChat](https://docs.swarms.world/en/latest/swarms/structs/group_chat/)** | Agents collaborate and make decisions through a conversational interface. | Real-time collaborative decision-making, negotiations, brainstorming. |
|
||||||
|
| **[ForestSwarm](https://docs.swarms.world/en/latest/swarms/structs/forest_swarm/)** | Dynamically selects the most suitable agent or tree of agents for a given task. | Task routing, optimizing for expertise, complex decision-making trees. |
|
||||||
|
| **[SpreadSheetSwarm](https://docs.swarms.world/en/latest/swarms/structs/spreadsheet_swarm/)** | Manages thousands of agents concurrently, tracking tasks and outputs in a structured format. | Massive-scale parallel operations, large-scale data generation and analysis. |
|
||||||
|
| **[SwarmRouter](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/)** | Universal orchestrator that provides a single interface to run any type of swarm with dynamic selection. | Simplifying complex workflows, switching between swarm strategies, unified multi-agent management. |
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
|
### SequentialWorkflow
|
||||||
|
|
||||||
|
A `SequentialWorkflow` executes tasks in a strict order, forming a pipeline where each agent builds upon the work of the previous one. `SequentialWorkflow` is Ideal for processes that have clear, ordered steps. This ensures that tasks with dependencies are handled correctly.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, SequentialWorkflow
|
||||||
|
|
||||||
|
# Initialize agents for a 3-step process
|
||||||
|
# 1. Generate an idea
|
||||||
|
idea_generator = Agent(agent_name="IdeaGenerator", system_prompt="Generate a unique startup idea.", model_name="gpt-4o-mini")
|
||||||
|
# 2. Validate the idea
|
||||||
|
validator = Agent(agent_name="Validator", system_prompt="Take this startup idea and analyze its market viability.", model_name="gpt-4o-mini")
|
||||||
|
# 3. Create a pitch
|
||||||
|
pitch_creator = Agent(agent_name="PitchCreator", system_prompt="Write a 3-sentence elevator pitch for this validated startup idea.", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# Create the sequential workflow
|
||||||
|
workflow = SequentialWorkflow(agents=[idea_generator, validator, pitch_creator])
|
||||||
|
|
||||||
|
# Run the workflow
|
||||||
|
elevator_pitch = workflow.run()
|
||||||
|
print(elevator_pitch)
|
||||||
|
```
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
|
|
||||||
|
### ConcurrentWorkflow (with `SpreadSheetSwarm`)
|
||||||
|
|
||||||
|
A concurrent workflow runs multiple agents simultaneously. `SpreadSheetSwarm` is a powerful implementation that can manage thousands of concurrent agents and log their outputs to a CSV file. Use this architecture for high-throughput tasks that can be performed in parallel, drastically reducing execution time.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, SpreadSheetSwarm
|
||||||
|
|
||||||
|
# Define a list of tasks (e.g., social media posts to generate)
|
||||||
|
platforms = ["Twitter", "LinkedIn", "Instagram"]
|
||||||
|
|
||||||
|
# Create an agent for each task
|
||||||
|
agents = [
|
||||||
|
Agent(
|
||||||
|
agent_name=f"{platform}-Marketer",
|
||||||
|
system_prompt=f"Generate a real estate marketing post for {platform}.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
)
|
||||||
|
for platform in platforms
|
||||||
|
]
|
||||||
|
|
||||||
|
# Initialize the swarm to run these agents concurrently
|
||||||
|
swarm = SpreadSheetSwarm(
|
||||||
|
agents=agents,
|
||||||
|
autosave_on=True,
|
||||||
|
save_file_path="marketing_posts.csv",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the swarm with a single, shared task description
|
||||||
|
property_description = "A beautiful 3-bedroom house in sunny California."
|
||||||
|
swarm.run(task=f"Generate a post about: {property_description}")
|
||||||
|
# Check marketing_posts.csv for the results!
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### AgentRearrange
|
||||||
|
|
||||||
|
Inspired by `einsum`, `AgentRearrange` lets you define complex, non-linear relationships between agents using a simple string-based syntax. [Learn more](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/). This architecture is Perfect for orchestrating dynamic workflows where agents might work in parallel, sequence, or a combination of both.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, AgentRearrange
|
||||||
|
|
||||||
|
# Define agents
|
||||||
|
researcher = Agent(agent_name="researcher", model_name="gpt-4o-mini")
|
||||||
|
writer = Agent(agent_name="writer", model_name="gpt-4o-mini")
|
||||||
|
editor = Agent(agent_name="editor", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# Define a flow: researcher sends work to both writer and editor simultaneously
|
||||||
|
# This is a one-to-many relationship
|
||||||
|
flow = "researcher -> writer, editor"
|
||||||
|
|
||||||
|
# Create the rearrangement system
|
||||||
|
rearrange_system = AgentRearrange(
|
||||||
|
agents=[researcher, writer, editor],
|
||||||
|
flow=flow,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the system
|
||||||
|
# The researcher will generate content, and then both the writer and editor
|
||||||
|
# will process that content in parallel.
|
||||||
|
outputs = rearrange_system.run("Analyze the impact of AI on modern cinema.")
|
||||||
|
print(outputs)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
<!--
|
||||||
|
### GraphWorkflow
|
||||||
|
|
||||||
|
`GraphWorkflow` orchestrates tasks using a Directed Acyclic Graph (DAG), allowing you to manage complex dependencies where some tasks must wait for others to complete.
|
||||||
|
|
||||||
|
**Description:** Essential for building sophisticated pipelines, like in software development or complex project management, where task order and dependencies are critical.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, GraphWorkflow, Node, Edge, NodeType
|
||||||
|
|
||||||
|
# Define agents and a simple python function as nodes
|
||||||
|
code_generator = Agent(agent_name="CodeGenerator", system_prompt="Write Python code for the given task.", model_name="gpt-4o-mini")
|
||||||
|
code_tester = Agent(agent_name="CodeTester", system_prompt="Test the given Python code and find bugs.", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# Create nodes for the graph
|
||||||
|
node1 = Node(id="generator", agent=code_generator)
|
||||||
|
node2 = Node(id="tester", agent=code_tester)
|
||||||
|
|
||||||
|
# Create the graph and define the dependency
|
||||||
|
graph = GraphWorkflow()
|
||||||
|
graph.add_nodes([node1, node2])
|
||||||
|
graph.add_edge(Edge(source="generator", target="tester")) # Tester runs after generator
|
||||||
|
|
||||||
|
# Set entry and end points
|
||||||
|
graph.set_entry_points(["generator"])
|
||||||
|
graph.set_end_points(["tester"])
|
||||||
|
|
||||||
|
# Run the graph workflow
|
||||||
|
results = graph.run("Create a function that calculates the factorial of a number.")
|
||||||
|
print(results)
|
||||||
|
``` -->
|
||||||
|
|
||||||
|
----
|
||||||
|
|
||||||
|
### SwarmRouter: The Universal Swarm Orchestrator
|
||||||
|
|
||||||
|
The `SwarmRouter` simplifies building complex workflows by providing a single interface to run any type of swarm. Instead of importing and managing different swarm classes, you can dynamically select the one you need just by changing the `swarm_type` parameter. [Read the full documentation](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/)
|
||||||
|
|
||||||
|
This makes your code cleaner and more flexible, allowing you to switch between different multi-agent strategies with ease. Here's a complete example that shows how to define agents and then use `SwarmRouter` to execute the same task using different collaborative strategies.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.swarm_router import SwarmRouter, SwarmType
|
||||||
|
|
||||||
|
# Define a few generic agents
|
||||||
|
writer = Agent(agent_name="Writer", system_prompt="You are a creative writer.", model_name="gpt-4o-mini")
|
||||||
|
editor = Agent(agent_name="Editor", system_prompt="You are an expert editor for stories.", model_name="gpt-4o-mini")
|
||||||
|
reviewer = Agent(agent_name="Reviewer", system_prompt="You are a final reviewer who gives a score.", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# The agents and task will be the same for all examples
|
||||||
|
agents = [writer, editor, reviewer]
|
||||||
|
task = "Write a short story about a robot who discovers music."
|
||||||
|
|
||||||
|
# --- Example 1: SequentialWorkflow ---
|
||||||
|
# Agents run one after another in a chain: Writer -> Editor -> Reviewer.
|
||||||
|
print("Running a Sequential Workflow...")
|
||||||
|
sequential_router = SwarmRouter(swarm_type=SwarmType.SequentialWorkflow, agents=agents)
|
||||||
|
sequential_output = sequential_router.run(task)
|
||||||
|
print(f"Final Sequential Output:\n{sequential_output}\n")
|
||||||
|
|
||||||
|
# --- Example 2: ConcurrentWorkflow ---
|
||||||
|
# All agents receive the same initial task and run at the same time.
|
||||||
|
print("Running a Concurrent Workflow...")
|
||||||
|
concurrent_router = SwarmRouter(swarm_type=SwarmType.ConcurrentWorkflow, agents=agents)
|
||||||
|
concurrent_outputs = concurrent_router.run(task)
|
||||||
|
# This returns a dictionary of each agent's output
|
||||||
|
for agent_name, output in concurrent_outputs.items():
|
||||||
|
print(f"Output from {agent_name}:\n{output}\n")
|
||||||
|
|
||||||
|
# --- Example 3: MixtureOfAgents ---
|
||||||
|
# All agents run in parallel, and a special 'aggregator' agent synthesizes their outputs.
|
||||||
|
print("Running a Mixture of Agents Workflow...")
|
||||||
|
aggregator = Agent(
|
||||||
|
agent_name="Aggregator",
|
||||||
|
system_prompt="Combine the story, edits, and review into a final document.",
|
||||||
|
model_name="gpt-4o-mini"
|
||||||
|
)
|
||||||
|
moa_router = SwarmRouter(
|
||||||
|
swarm_type=SwarmType.MixtureOfAgents,
|
||||||
|
agents=agents,
|
||||||
|
aggregator_agent=aggregator, # MoA requires an aggregator
|
||||||
|
)
|
||||||
|
aggregated_output = moa_router.run(task)
|
||||||
|
print(f"Final Aggregated Output:\n{aggregated_output}\n")
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
The `SwarmRouter` is a powerful tool for simplifying multi-agent orchestration. It provides a consistent and flexible way to deploy different collaborative strategies, allowing you to build more sophisticated applications with less code.
|
||||||
|
|
||||||
|
-------
|
||||||
|
|
||||||
|
### MixtureOfAgents (MoA)
|
||||||
|
|
||||||
|
The `MixtureOfAgents` architecture processes tasks by feeding them to multiple "expert" agents in parallel. Their diverse outputs are then synthesized by an aggregator agent to produce a final, high-quality result. [Learn more here](https://docs.swarms.world/en/latest/swarms/examples/moa_example/)
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, MixtureOfAgents
|
||||||
|
|
||||||
|
# Define expert agents
|
||||||
|
financial_analyst = Agent(agent_name="FinancialAnalyst", system_prompt="Analyze financial data.", model_name="gpt-4o-mini")
|
||||||
|
market_analyst = Agent(agent_name="MarketAnalyst", system_prompt="Analyze market trends.", model_name="gpt-4o-mini")
|
||||||
|
risk_analyst = Agent(agent_name="RiskAnalyst", system_prompt="Analyze investment risks.", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# Define the aggregator agent
|
||||||
|
aggregator = Agent(
|
||||||
|
agent_name="InvestmentAdvisor",
|
||||||
|
system_prompt="Synthesize the financial, market, and risk analyses to provide a final investment recommendation.",
|
||||||
|
model_name="gpt-4o-mini"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create the MoA swarm
|
||||||
|
moa_swarm = MixtureOfAgents(
|
||||||
|
agents=[financial_analyst, market_analyst, risk_analyst],
|
||||||
|
aggregator_agent=aggregator,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the swarm
|
||||||
|
recommendation = moa_swarm.run("Should we invest in NVIDIA stock right now?")
|
||||||
|
print(recommendation)
|
||||||
|
```
|
||||||
|
|
||||||
|
----
|
||||||
|
|
||||||
|
### GroupChat
|
||||||
|
|
||||||
|
`GroupChat` creates a conversational environment where multiple agents can interact, discuss, and collaboratively solve a problem. You can define the speaking order or let it be determined dynamically. This architecture is ideal for tasks that benefit from debate and multi-perspective reasoning, such as contract negotiation, brainstorming, or complex decision-making.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent, GroupChat
|
||||||
|
|
||||||
|
# Define agents for a debate
|
||||||
|
tech_optimist = Agent(agent_name="TechOptimist", system_prompt="Argue for the benefits of AI in society.", model_name="gpt-4o-mini")
|
||||||
|
tech_critic = Agent(agent_name="TechCritic", system_prompt="Argue against the unchecked advancement of AI.", model_name="gpt-4o-mini")
|
||||||
|
|
||||||
|
# Create the group chat
|
||||||
|
chat = GroupChat(
|
||||||
|
agents=[tech_optimist, tech_critic],
|
||||||
|
max_loops=4, # Limit the number of turns in the conversation
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the chat with an initial topic
|
||||||
|
conversation_history = chat.run(
|
||||||
|
"Let's discuss the societal impact of artificial intelligence."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Print the full conversation
|
||||||
|
for message in conversation_history:
|
||||||
|
print(f"[{message['agent_name']}]: {message['content']}")
|
||||||
|
```
|
||||||
|
|
||||||
|
|
@ -0,0 +1,884 @@
|
|||||||
|
# Agents Introduction
|
||||||
|
|
||||||
|
The Agent class is the core component of the Swarms framework, designed to create intelligent, autonomous AI agents capable of handling complex tasks through multi-modal processing, tool integration, and structured outputs. This comprehensive guide covers all aspects of the Agent class, from basic setup to advanced features.
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
1. [Prerequisites & Installation](#prerequisites--installation)
|
||||||
|
2. [Basic Agent Configuration](#basic-agent-configuration)
|
||||||
|
3. [Multi-Modal Capabilities](#multi-modal-capabilities)
|
||||||
|
4. [Tool Integration](#tool-integration)
|
||||||
|
5. [Structured Outputs](#structured-outputs)
|
||||||
|
6. [Advanced Features](#advanced-features)
|
||||||
|
7. [Best Practices](#best-practices)
|
||||||
|
8. [Complete Examples](#complete-examples)
|
||||||
|
|
||||||
|
## Prerequisites & Installation
|
||||||
|
|
||||||
|
### System Requirements
|
||||||
|
|
||||||
|
- Python 3.7+
|
||||||
|
|
||||||
|
- OpenAI API key (for GPT models)
|
||||||
|
|
||||||
|
- Anthropic API key (for Claude models)
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip3 install -U swarms
|
||||||
|
```
|
||||||
|
|
||||||
|
### Environment Setup
|
||||||
|
|
||||||
|
Create a `.env` file with your API keys:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
OPENAI_API_KEY="your-openai-api-key"
|
||||||
|
ANTHROPIC_API_KEY="your-anthropic-api-key"
|
||||||
|
WORKSPACE_DIR="agent_workspace"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Basic Agent Configuration
|
||||||
|
|
||||||
|
### Core Agent Structure
|
||||||
|
|
||||||
|
The Agent class provides a comprehensive set of parameters for customization:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Basic agent initialization
|
||||||
|
agent = Agent(
|
||||||
|
agent_name="MyAgent",
|
||||||
|
agent_description="A specialized AI agent for specific tasks",
|
||||||
|
system_prompt="You are a helpful assistant...",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
max_tokens=4096,
|
||||||
|
temperature=0.7,
|
||||||
|
output_type="str",
|
||||||
|
safety_prompt_on=True
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Key Configuration Parameters
|
||||||
|
|
||||||
|
| Parameter | Type | Description | Default |
|
||||||
|
|-----------|------|-------------|---------|
|
||||||
|
| `agent_name` | str | Unique identifier for the agent | Required |
|
||||||
|
| `agent_description` | str | Detailed description of capabilities | Required |
|
||||||
|
| `system_prompt` | str | Core instructions defining behavior | Required |
|
||||||
|
| `model_name` | str | AI model to use | "gpt-4o-mini" |
|
||||||
|
| `max_loops` | int | Maximum execution loops | 1 |
|
||||||
|
| `max_tokens` | int | Maximum response tokens | 4096 |
|
||||||
|
| `temperature` | float | Response creativity (0-1) | 0.7 |
|
||||||
|
| `output_type` | str | Response format type | "str" |
|
||||||
|
| `multi_modal` | bool | Enable image processing | False |
|
||||||
|
| `safety_prompt_on` | bool | Enable safety checks | True |
|
||||||
|
|
||||||
|
### Simple Example
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Create a basic financial advisor agent
|
||||||
|
financial_agent = Agent(
|
||||||
|
agent_name="Financial-Advisor",
|
||||||
|
agent_description="Personal finance and investment advisor",
|
||||||
|
system_prompt="""You are an expert financial advisor with deep knowledge of:
|
||||||
|
- Investment strategies and portfolio management
|
||||||
|
- Risk assessment and mitigation
|
||||||
|
- Market analysis and trends
|
||||||
|
- Financial planning and budgeting
|
||||||
|
|
||||||
|
Provide clear, actionable advice while considering risk tolerance.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.3,
|
||||||
|
output_type="str"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Run the agent
|
||||||
|
response = financial_agent.run("What are the best investment strategies for a 30-year-old?")
|
||||||
|
print(response)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Multi-Modal Capabilities
|
||||||
|
|
||||||
|
### Image Processing
|
||||||
|
|
||||||
|
The Agent class supports comprehensive image analysis through vision-enabled models:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Create a vision-enabled agent
|
||||||
|
vision_agent = Agent(
|
||||||
|
agent_name="Vision-Analyst",
|
||||||
|
agent_description="Advanced image analysis and quality control agent",
|
||||||
|
system_prompt="""You are an expert image analyst capable of:
|
||||||
|
- Detailed visual inspection and quality assessment
|
||||||
|
- Object detection and classification
|
||||||
|
- Scene understanding and context analysis
|
||||||
|
- Defect identification and reporting
|
||||||
|
|
||||||
|
Provide comprehensive analysis with specific observations.""",
|
||||||
|
model_name="gpt-4o-mini", # Vision-enabled model
|
||||||
|
multi_modal=True, # Enable multi-modal processing
|
||||||
|
max_loops=1,
|
||||||
|
output_type="str"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Analyze a single image
|
||||||
|
response = vision_agent.run(
|
||||||
|
task="Analyze this image for quality control purposes",
|
||||||
|
img="path/to/image.jpg"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Process multiple images
|
||||||
|
response = vision_agent.run(
|
||||||
|
task="Compare these images and identify differences",
|
||||||
|
imgs=["image1.jpg", "image2.jpg", "image3.jpg"],
|
||||||
|
summarize_multiple_images=True
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Supported Image Formats
|
||||||
|
|
||||||
|
| Format | Description | Max Size |
|
||||||
|
|--------|-------------|----------|
|
||||||
|
| JPEG/JPG | Standard compressed format | 20MB |
|
||||||
|
| PNG | Lossless with transparency | 20MB |
|
||||||
|
| GIF | Animated (first frame only) | 20MB |
|
||||||
|
| WebP | Modern efficient format | 20MB |
|
||||||
|
|
||||||
|
### Quality Control Example
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.prompts.logistics import Quality_Control_Agent_Prompt
|
||||||
|
|
||||||
|
def security_analysis(danger_level: str) -> str:
|
||||||
|
"""Analyze security danger level and return appropriate response."""
|
||||||
|
danger_responses = {
|
||||||
|
"low": "No immediate danger detected",
|
||||||
|
"medium": "Moderate security concern identified",
|
||||||
|
"high": "Critical security threat detected",
|
||||||
|
None: "No danger level assessment available"
|
||||||
|
}
|
||||||
|
return danger_responses.get(danger_level, "Unknown danger level")
|
||||||
|
|
||||||
|
# Quality control agent with tool integration
|
||||||
|
quality_agent = Agent(
|
||||||
|
agent_name="Quality-Control-Agent",
|
||||||
|
agent_description="Advanced quality control and security analysis agent",
|
||||||
|
system_prompt=f"""
|
||||||
|
{Quality_Control_Agent_Prompt}
|
||||||
|
|
||||||
|
You have access to security analysis tools. When analyzing images:
|
||||||
|
1. Identify potential safety hazards
|
||||||
|
2. Assess quality standards compliance
|
||||||
|
3. Determine appropriate danger levels (low, medium, high)
|
||||||
|
4. Use the security_analysis function for threat assessment
|
||||||
|
""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
multi_modal=True,
|
||||||
|
max_loops=1,
|
||||||
|
tools=[security_analysis]
|
||||||
|
)
|
||||||
|
|
||||||
|
# Analyze factory image
|
||||||
|
response = quality_agent.run(
|
||||||
|
task="Analyze this factory image for safety and quality issues",
|
||||||
|
img="factory_floor.jpg"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tool Integration
|
||||||
|
|
||||||
|
### Creating Custom Tools
|
||||||
|
|
||||||
|
Tools are Python functions that extend your agent's capabilities:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import json
|
||||||
|
import requests
|
||||||
|
from typing import Optional, Dict, Any
|
||||||
|
|
||||||
|
def get_weather_data(city: str, country: Optional[str] = None) -> str:
|
||||||
|
"""
|
||||||
|
Get current weather data for a specified city.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
city (str): The city name
|
||||||
|
country (Optional[str]): Country code (e.g., 'US', 'UK')
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: JSON formatted weather data
|
||||||
|
|
||||||
|
Example:
|
||||||
|
>>> weather = get_weather_data("San Francisco", "US")
|
||||||
|
>>> print(weather)
|
||||||
|
{"temperature": 18, "condition": "partly cloudy", ...}
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# API call logic here
|
||||||
|
weather_data = {
|
||||||
|
"city": city,
|
||||||
|
"country": country,
|
||||||
|
"temperature": 18,
|
||||||
|
"condition": "partly cloudy",
|
||||||
|
"humidity": 65,
|
||||||
|
"wind_speed": 12
|
||||||
|
}
|
||||||
|
return json.dumps(weather_data, indent=2)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": f"Weather API error: {str(e)}"})
|
||||||
|
|
||||||
|
def calculate_portfolio_metrics(prices: list, weights: list) -> str:
|
||||||
|
"""
|
||||||
|
Calculate portfolio performance metrics.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
prices (list): List of asset prices
|
||||||
|
weights (list): List of portfolio weights
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: JSON formatted portfolio metrics
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
# Portfolio calculation logic
|
||||||
|
portfolio_value = sum(p * w for p, w in zip(prices, weights))
|
||||||
|
metrics = {
|
||||||
|
"total_value": portfolio_value,
|
||||||
|
"weighted_average": portfolio_value / sum(weights),
|
||||||
|
"asset_count": len(prices)
|
||||||
|
}
|
||||||
|
return json.dumps(metrics, indent=2)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": f"Calculation error: {str(e)}"})
|
||||||
|
```
|
||||||
|
|
||||||
|
### Tool Integration Example
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Create agent with custom tools
|
||||||
|
multi_tool_agent = Agent(
|
||||||
|
agent_name="Multi-Tool-Assistant",
|
||||||
|
agent_description="Versatile assistant with weather and financial tools",
|
||||||
|
system_prompt="""You are a versatile assistant with access to:
|
||||||
|
- Weather data retrieval for any city
|
||||||
|
- Portfolio analysis and financial calculations
|
||||||
|
|
||||||
|
Use these tools to provide comprehensive assistance.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
tools=[get_weather_data, calculate_portfolio_metrics]
|
||||||
|
)
|
||||||
|
|
||||||
|
# Use the agent with tools
|
||||||
|
response = multi_tool_agent.run(
|
||||||
|
"What's the weather in New York and calculate metrics for a portfolio with prices [100, 150, 200] and weights [0.3, 0.4, 0.3]?"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### API Integration Tools
|
||||||
|
|
||||||
|
```python
|
||||||
|
import requests
|
||||||
|
import json
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
def get_cryptocurrency_price(coin_id: str, vs_currency: str = "usd") -> str:
|
||||||
|
"""Get current cryptocurrency price from CoinGecko API."""
|
||||||
|
try:
|
||||||
|
url = "https://api.coingecko.com/api/v3/simple/price"
|
||||||
|
params = {
|
||||||
|
"ids": coin_id,
|
||||||
|
"vs_currencies": vs_currency,
|
||||||
|
"include_market_cap": True,
|
||||||
|
"include_24hr_vol": True,
|
||||||
|
"include_24hr_change": True
|
||||||
|
}
|
||||||
|
|
||||||
|
response = requests.get(url, params=params, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return json.dumps(response.json(), indent=2)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": f"API error: {str(e)}"})
|
||||||
|
|
||||||
|
def get_top_cryptocurrencies(limit: int = 10) -> str:
|
||||||
|
"""Get top cryptocurrencies by market cap."""
|
||||||
|
try:
|
||||||
|
url = "https://api.coingecko.com/api/v3/coins/markets"
|
||||||
|
params = {
|
||||||
|
"vs_currency": "usd",
|
||||||
|
"order": "market_cap_desc",
|
||||||
|
"per_page": limit,
|
||||||
|
"page": 1
|
||||||
|
}
|
||||||
|
|
||||||
|
response = requests.get(url, params=params, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return json.dumps(response.json(), indent=2)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": f"API error: {str(e)}"})
|
||||||
|
|
||||||
|
# Crypto analysis agent
|
||||||
|
crypto_agent = Agent(
|
||||||
|
agent_name="Crypto-Analysis-Agent",
|
||||||
|
agent_description="Cryptocurrency market analysis and price tracking agent",
|
||||||
|
system_prompt="""You are a cryptocurrency analysis expert with access to:
|
||||||
|
- Real-time price data for any cryptocurrency
|
||||||
|
- Market capitalization rankings
|
||||||
|
- Trading volume and price change data
|
||||||
|
|
||||||
|
Provide insightful market analysis and investment guidance.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
tools=[get_cryptocurrency_price, get_top_cryptocurrencies]
|
||||||
|
)
|
||||||
|
|
||||||
|
# Analyze crypto market
|
||||||
|
response = crypto_agent.run("Analyze the current Bitcoin price and show me the top 5 cryptocurrencies")
|
||||||
|
```
|
||||||
|
|
||||||
|
## Structured Outputs
|
||||||
|
|
||||||
|
### Function Schema Definition
|
||||||
|
|
||||||
|
Define structured outputs using OpenAI's function calling format:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Define function schemas for structured outputs
|
||||||
|
stock_analysis_schema = {
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "analyze_stock_performance",
|
||||||
|
"description": "Analyze stock performance with detailed metrics",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"ticker": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Stock ticker symbol (e.g., AAPL, GOOGL)"
|
||||||
|
},
|
||||||
|
"analysis_type": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["technical", "fundamental", "comprehensive"],
|
||||||
|
"description": "Type of analysis to perform"
|
||||||
|
},
|
||||||
|
"time_period": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["1d", "1w", "1m", "3m", "1y"],
|
||||||
|
"description": "Time period for analysis"
|
||||||
|
},
|
||||||
|
"metrics": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["price", "volume", "pe_ratio", "market_cap", "volatility"]
|
||||||
|
},
|
||||||
|
"description": "Metrics to include in analysis"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["ticker", "analysis_type"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
portfolio_optimization_schema = {
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "optimize_portfolio",
|
||||||
|
"description": "Optimize portfolio allocation based on risk and return",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"assets": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"symbol": {"type": "string"},
|
||||||
|
"current_weight": {"type": "number"},
|
||||||
|
"expected_return": {"type": "number"},
|
||||||
|
"risk_level": {"type": "string", "enum": ["low", "medium", "high"]}
|
||||||
|
},
|
||||||
|
"required": ["symbol", "current_weight"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"risk_tolerance": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["conservative", "moderate", "aggressive"]
|
||||||
|
},
|
||||||
|
"investment_horizon": {
|
||||||
|
"type": "integer",
|
||||||
|
"minimum": 1,
|
||||||
|
"maximum": 30,
|
||||||
|
"description": "Investment time horizon in years"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["assets", "risk_tolerance"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Create agent with structured outputs
|
||||||
|
structured_agent = Agent(
|
||||||
|
agent_name="Structured-Financial-Agent",
|
||||||
|
agent_description="Financial analysis agent with structured output capabilities",
|
||||||
|
system_prompt="""You are a financial analysis expert that provides structured outputs.
|
||||||
|
Use the provided function schemas to format your responses consistently.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
tools_list_dictionary=[stock_analysis_schema, portfolio_optimization_schema]
|
||||||
|
)
|
||||||
|
|
||||||
|
# Generate structured analysis
|
||||||
|
response = structured_agent.run(
|
||||||
|
"Analyze Apple stock (AAPL) performance with comprehensive analysis for the last 3 months"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Advanced Features
|
||||||
|
|
||||||
|
### Dynamic Temperature Control
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Agent with dynamic temperature adjustment
|
||||||
|
adaptive_agent = Agent(
|
||||||
|
agent_name="Adaptive-Response-Agent",
|
||||||
|
agent_description="Agent that adjusts response creativity based on context",
|
||||||
|
system_prompt="You are an adaptive AI that adjusts your response style based on the task complexity.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
dynamic_temperature_enabled=True, # Enable adaptive temperature
|
||||||
|
max_loops=1,
|
||||||
|
output_type="str"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Output Type Configurations
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Different output type examples
|
||||||
|
json_agent = Agent(
|
||||||
|
agent_name="JSON-Agent",
|
||||||
|
system_prompt="Always respond in valid JSON format",
|
||||||
|
output_type="json"
|
||||||
|
)
|
||||||
|
|
||||||
|
streaming_agent = Agent(
|
||||||
|
agent_name="Streaming-Agent",
|
||||||
|
system_prompt="Provide detailed streaming responses",
|
||||||
|
output_type="str-all-except-first"
|
||||||
|
)
|
||||||
|
|
||||||
|
final_only_agent = Agent(
|
||||||
|
agent_name="Final-Only-Agent",
|
||||||
|
system_prompt="Provide only the final result",
|
||||||
|
output_type="final"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Safety and Content Filtering
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Agent with enhanced safety features
|
||||||
|
safe_agent = Agent(
|
||||||
|
agent_name="Safe-Agent",
|
||||||
|
agent_description="Agent with comprehensive safety measures",
|
||||||
|
system_prompt="You are a helpful, harmless, and honest AI assistant.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
safety_prompt_on=True, # Enable safety prompts
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.3 # Lower temperature for more consistent, safe responses
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
### Error Handling and Robustness
|
||||||
|
|
||||||
|
```python
|
||||||
|
import logging
|
||||||
|
from swarms import Agent
|
||||||
|
|
||||||
|
# Configure logging
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
def robust_agent_execution(agent, task, max_retries=3):
|
||||||
|
"""Execute agent with retry logic and error handling."""
|
||||||
|
for attempt in range(max_retries):
|
||||||
|
try:
|
||||||
|
response = agent.run(task)
|
||||||
|
logger.info(f"Agent execution successful on attempt {attempt + 1}")
|
||||||
|
return response
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Attempt {attempt + 1} failed: {str(e)}")
|
||||||
|
if attempt == max_retries - 1:
|
||||||
|
raise
|
||||||
|
time.sleep(2 ** attempt) # Exponential backoff
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Example usage
|
||||||
|
try:
|
||||||
|
result = robust_agent_execution(agent, "Analyze market trends")
|
||||||
|
print(result)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Agent execution failed: {e}")
|
||||||
|
```
|
||||||
|
|
||||||
|
### Performance Optimization
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
import time
|
||||||
|
|
||||||
|
# Optimized agent configuration
|
||||||
|
optimized_agent = Agent(
|
||||||
|
agent_name="Optimized-Agent",
|
||||||
|
agent_description="Performance-optimized agent configuration",
|
||||||
|
system_prompt="You are an efficient AI assistant optimized for performance.",
|
||||||
|
model_name="gpt-4o-mini", # Faster model
|
||||||
|
max_loops=1, # Minimize loops
|
||||||
|
max_tokens=2048, # Reasonable token limit
|
||||||
|
temperature=0.5, # Balanced creativity
|
||||||
|
output_type="str"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Batch processing example
|
||||||
|
def process_tasks_batch(agent, tasks, batch_size=5):
|
||||||
|
"""Process multiple tasks efficiently."""
|
||||||
|
results = []
|
||||||
|
for i in range(0, len(tasks), batch_size):
|
||||||
|
batch = tasks[i:i + batch_size]
|
||||||
|
batch_results = []
|
||||||
|
|
||||||
|
for task in batch:
|
||||||
|
start_time = time.time()
|
||||||
|
result = agent.run(task)
|
||||||
|
execution_time = time.time() - start_time
|
||||||
|
|
||||||
|
batch_results.append({
|
||||||
|
"task": task,
|
||||||
|
"result": result,
|
||||||
|
"execution_time": execution_time
|
||||||
|
})
|
||||||
|
|
||||||
|
results.extend(batch_results)
|
||||||
|
time.sleep(1) # Rate limiting
|
||||||
|
|
||||||
|
return results
|
||||||
|
```
|
||||||
|
|
||||||
|
## Complete Examples
|
||||||
|
|
||||||
|
### Multi-Modal Quality Control System
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.prompts.logistics import Quality_Control_Agent_Prompt
|
||||||
|
|
||||||
|
def security_analysis(danger_level: str) -> str:
|
||||||
|
"""Analyze security danger level and return appropriate response."""
|
||||||
|
responses = {
|
||||||
|
"low": "✅ No immediate danger detected - Safe to proceed",
|
||||||
|
"medium": "⚠️ Moderate security concern - Requires attention",
|
||||||
|
"high": "🚨 Critical security threat - Immediate action required",
|
||||||
|
None: "❓ No danger level assessment available"
|
||||||
|
}
|
||||||
|
return responses.get(danger_level, "Unknown danger level")
|
||||||
|
|
||||||
|
def quality_assessment(quality_score: int) -> str:
|
||||||
|
"""Assess quality based on numerical score (1-10)."""
|
||||||
|
if quality_score >= 8:
|
||||||
|
return "✅ Excellent quality - Meets all standards"
|
||||||
|
elif quality_score >= 6:
|
||||||
|
return "⚠️ Good quality - Minor improvements needed"
|
||||||
|
elif quality_score >= 4:
|
||||||
|
return "❌ Poor quality - Significant issues identified"
|
||||||
|
else:
|
||||||
|
return "🚨 Critical quality failure - Immediate attention required"
|
||||||
|
|
||||||
|
# Advanced quality control agent
|
||||||
|
quality_control_system = Agent(
|
||||||
|
agent_name="Advanced-Quality-Control-System",
|
||||||
|
agent_description="Comprehensive quality control and security analysis system",
|
||||||
|
system_prompt=f"""
|
||||||
|
{Quality_Control_Agent_Prompt}
|
||||||
|
|
||||||
|
You are an advanced quality control system with the following capabilities:
|
||||||
|
|
||||||
|
1. Visual Inspection: Analyze images for defects, compliance, and safety
|
||||||
|
2. Security Assessment: Identify potential security threats and hazards
|
||||||
|
3. Quality Scoring: Provide numerical quality ratings (1-10 scale)
|
||||||
|
4. Detailed Reporting: Generate comprehensive analysis reports
|
||||||
|
|
||||||
|
When analyzing images:
|
||||||
|
- Identify specific defects or issues
|
||||||
|
- Assess compliance with safety standards
|
||||||
|
- Determine appropriate danger levels (low, medium, high)
|
||||||
|
- Provide quality scores and recommendations
|
||||||
|
- Use available tools for detailed analysis
|
||||||
|
|
||||||
|
Always provide specific, actionable feedback.
|
||||||
|
""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
multi_modal=True,
|
||||||
|
max_loops=1,
|
||||||
|
tools=[security_analysis, quality_assessment],
|
||||||
|
output_type="str"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Process factory images
|
||||||
|
factory_images = ["factory_floor.jpg", "assembly_line.jpg", "safety_equipment.jpg"]
|
||||||
|
|
||||||
|
for image in factory_images:
|
||||||
|
print(f"\n--- Analyzing {image} ---")
|
||||||
|
response = quality_control_system.run(
|
||||||
|
task=f"Perform comprehensive quality control analysis of this image. Assess safety, quality, and provide specific recommendations.",
|
||||||
|
img=image
|
||||||
|
)
|
||||||
|
print(response)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Advanced Financial Analysis Agent
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
import json
|
||||||
|
import requests
|
||||||
|
|
||||||
|
def get_market_data(symbol: str, period: str = "1y") -> str:
|
||||||
|
"""Get comprehensive market data for a symbol."""
|
||||||
|
# Simulated market data (replace with real API)
|
||||||
|
market_data = {
|
||||||
|
"symbol": symbol,
|
||||||
|
"current_price": 150.25,
|
||||||
|
"change_percent": 2.5,
|
||||||
|
"volume": 1000000,
|
||||||
|
"market_cap": 2500000000,
|
||||||
|
"pe_ratio": 25.5,
|
||||||
|
"dividend_yield": 1.8,
|
||||||
|
"52_week_high": 180.50,
|
||||||
|
"52_week_low": 120.30
|
||||||
|
}
|
||||||
|
return json.dumps(market_data, indent=2)
|
||||||
|
|
||||||
|
def calculate_risk_metrics(prices: list, benchmark_prices: list) -> str:
|
||||||
|
"""Calculate risk metrics for a portfolio."""
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
try:
|
||||||
|
returns = np.diff(prices) / prices[:-1]
|
||||||
|
benchmark_returns = np.diff(benchmark_prices) / benchmark_prices[:-1]
|
||||||
|
|
||||||
|
volatility = np.std(returns) * np.sqrt(252) # Annualized
|
||||||
|
sharpe_ratio = (np.mean(returns) / np.std(returns)) * np.sqrt(252)
|
||||||
|
max_drawdown = np.max(np.maximum.accumulate(prices) - prices) / np.max(prices)
|
||||||
|
|
||||||
|
beta = np.cov(returns, benchmark_returns)[0, 1] / np.var(benchmark_returns)
|
||||||
|
|
||||||
|
risk_metrics = {
|
||||||
|
"volatility": float(volatility),
|
||||||
|
"sharpe_ratio": float(sharpe_ratio),
|
||||||
|
"max_drawdown": float(max_drawdown),
|
||||||
|
"beta": float(beta)
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.dumps(risk_metrics, indent=2)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": f"Risk calculation error: {str(e)}"})
|
||||||
|
|
||||||
|
# Financial analysis schemas
|
||||||
|
financial_analysis_schema = {
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "comprehensive_financial_analysis",
|
||||||
|
"description": "Perform comprehensive financial analysis with structured output",
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"analysis_summary": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"overall_rating": {"type": "string", "enum": ["buy", "hold", "sell"]},
|
||||||
|
"confidence_level": {"type": "number", "minimum": 0, "maximum": 100},
|
||||||
|
"key_strengths": {"type": "array", "items": {"type": "string"}},
|
||||||
|
"key_concerns": {"type": "array", "items": {"type": "string"}},
|
||||||
|
"price_target": {"type": "number"},
|
||||||
|
"risk_level": {"type": "string", "enum": ["low", "medium", "high"]}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"technical_analysis": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"trend_direction": {"type": "string", "enum": ["bullish", "bearish", "neutral"]},
|
||||||
|
"support_levels": {"type": "array", "items": {"type": "number"}},
|
||||||
|
"resistance_levels": {"type": "array", "items": {"type": "number"}},
|
||||||
|
"momentum_indicators": {"type": "array", "items": {"type": "string"}}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": ["analysis_summary", "technical_analysis"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Advanced financial agent
|
||||||
|
financial_analyst = Agent(
|
||||||
|
agent_name="Advanced-Financial-Analyst",
|
||||||
|
agent_description="Comprehensive financial analysis and investment advisory agent",
|
||||||
|
system_prompt="""You are an expert financial analyst with advanced capabilities in:
|
||||||
|
|
||||||
|
- Fundamental analysis and valuation
|
||||||
|
- Technical analysis and chart patterns
|
||||||
|
- Risk assessment and portfolio optimization
|
||||||
|
- Market sentiment analysis
|
||||||
|
- Economic indicator interpretation
|
||||||
|
|
||||||
|
Your analysis should be:
|
||||||
|
- Data-driven and objective
|
||||||
|
- Risk-aware and practical
|
||||||
|
- Clearly structured and actionable
|
||||||
|
- Compliant with financial regulations
|
||||||
|
|
||||||
|
Use available tools to gather market data and calculate risk metrics.
|
||||||
|
Provide structured outputs using the defined schemas.""",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
tools=[get_market_data, calculate_risk_metrics],
|
||||||
|
tools_list_dictionary=[financial_analysis_schema],
|
||||||
|
output_type="json"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Comprehensive financial analysis
|
||||||
|
analysis_response = financial_analyst.run(
|
||||||
|
"Perform a comprehensive analysis of Apple Inc. (AAPL) including technical and fundamental analysis with structured recommendations"
|
||||||
|
)
|
||||||
|
|
||||||
|
print(json.dumps(json.loads(analysis_response), indent=2))
|
||||||
|
```
|
||||||
|
|
||||||
|
### Multi-Agent Collaboration System
|
||||||
|
|
||||||
|
```python
|
||||||
|
from swarms import Agent
|
||||||
|
import json
|
||||||
|
|
||||||
|
# Specialized agents for different tasks
|
||||||
|
research_agent = Agent(
|
||||||
|
agent_name="Research-Specialist",
|
||||||
|
agent_description="Market research and data analysis specialist",
|
||||||
|
system_prompt="You are a market research expert specializing in data collection and analysis.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.3
|
||||||
|
)
|
||||||
|
|
||||||
|
strategy_agent = Agent(
|
||||||
|
agent_name="Strategy-Advisor",
|
||||||
|
agent_description="Strategic planning and recommendation specialist",
|
||||||
|
system_prompt="You are a strategic advisor providing high-level recommendations based on research.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.5
|
||||||
|
)
|
||||||
|
|
||||||
|
execution_agent = Agent(
|
||||||
|
agent_name="Execution-Planner",
|
||||||
|
agent_description="Implementation and execution planning specialist",
|
||||||
|
system_prompt="You are an execution expert creating detailed implementation plans.",
|
||||||
|
model_name="gpt-4o-mini",
|
||||||
|
max_loops=1,
|
||||||
|
temperature=0.4
|
||||||
|
)
|
||||||
|
|
||||||
|
def collaborative_analysis(topic: str):
|
||||||
|
"""Perform collaborative analysis using multiple specialized agents."""
|
||||||
|
|
||||||
|
# Step 1: Research Phase
|
||||||
|
research_task = f"Conduct comprehensive research on {topic}. Provide key findings, market data, and trends."
|
||||||
|
research_results = research_agent.run(research_task)
|
||||||
|
|
||||||
|
# Step 2: Strategy Phase
|
||||||
|
strategy_task = f"Based on this research: {research_results}\n\nDevelop strategic recommendations for {topic}."
|
||||||
|
strategy_results = strategy_agent.run(strategy_task)
|
||||||
|
|
||||||
|
# Step 3: Execution Phase
|
||||||
|
execution_task = f"Create a detailed implementation plan based on:\nResearch: {research_results}\nStrategy: {strategy_results}"
|
||||||
|
execution_results = execution_agent.run(execution_task)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"research": research_results,
|
||||||
|
"strategy": strategy_results,
|
||||||
|
"execution": execution_results
|
||||||
|
}
|
||||||
|
|
||||||
|
# Example: Collaborative investment analysis
|
||||||
|
investment_analysis = collaborative_analysis("renewable energy sector investment opportunities")
|
||||||
|
|
||||||
|
for phase, results in investment_analysis.items():
|
||||||
|
print(f"\n=== {phase.upper()} PHASE ===")
|
||||||
|
print(results)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Support and Resources
|
||||||
|
|
||||||
|
Join our community of agent engineers and researchers for technical support, cutting-edge updates, and exclusive access to world-class agent engineering insights!
|
||||||
|
|
||||||
|
| Platform | Description | Link |
|
||||||
|
|----------|-------------|------|
|
||||||
|
| 📚 Documentation | Official documentation and guides | [docs.swarms.world](https://docs.swarms.world) |
|
||||||
|
| 📝 Blog | Latest updates and technical articles | [Medium](https://medium.com/@kyeg) |
|
||||||
|
| 💬 Discord | Live chat and community support | [Join Discord](https://discord.gg/jM3Z6M9uMq) |
|
||||||
|
| 🐦 Twitter | Latest news and announcements | [@kyegomez](https://twitter.com/kyegomez) |
|
||||||
|
| 👥 LinkedIn | Professional network and updates | [The Swarm Corporation](https://www.linkedin.com/company/the-swarm-corporation) |
|
||||||
|
| 📺 YouTube | Tutorials and demos | [Swarms Channel](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ) |
|
||||||
|
| 🎫 Events | Join our community events | [Sign up here](https://lu.ma/5p2jnc2v) |
|
||||||
|
| 🚀 Onboarding Session | Get onboarded with Kye Gomez, creator and lead maintainer of Swarms | [Book Session](https://cal.com/swarms/swarms-onboarding-session) |
|
||||||
|
|
||||||
|
### Getting Help
|
||||||
|
|
||||||
|
If you encounter issues or need assistance:
|
||||||
|
|
||||||
|
1. **Check the Documentation**: Start with the official docs for comprehensive guides
|
||||||
|
2. **Search Issues**: Look through existing GitHub issues for similar problems
|
||||||
|
3. **Join Discord**: Get real-time help from the community
|
||||||
|
4. **Create an Issue**: Report bugs or request features on GitHub
|
||||||
|
5. **Follow Updates**: Stay informed about new releases and improvements
|
||||||
|
|
||||||
|
### Contributing
|
||||||
|
|
||||||
|
We welcome contributions! Here's how to get involved:
|
||||||
|
|
||||||
|
- **Report Bugs**: Help us improve by reporting issues
|
||||||
|
|
||||||
|
- **Suggest Features**: Share your ideas for new capabilities
|
||||||
|
|
||||||
|
- **Submit Code**: Contribute improvements and new features
|
||||||
|
|
||||||
|
- **Improve Documentation**: Help make our docs better
|
||||||
|
|
||||||
|
- **Share Examples**: Show how you're using Swarms in your projects
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*This guide covers the essential aspects of the Swarms Agent class. For the most up-to-date information and advanced features, please refer to the official documentation and community resources.*
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,59 @@
|
|||||||
|
# Swarms API Rate Limits
|
||||||
|
|
||||||
|
The Swarms API implements rate limiting to ensure fair usage and system stability. Here are the current limits:
|
||||||
|
|
||||||
|
## Standard Rate Limits
|
||||||
|
|
||||||
|
- **General API Requests**: 100 requests per minute
|
||||||
|
- **Batch Operations**: Maximum 10 requests per batch for agent/swarm batch operations
|
||||||
|
|
||||||
|
## Rate Limit Response
|
||||||
|
|
||||||
|
When you exceed the rate limit, the API will return a 429 (Too Many Requests) status code with the following message:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"detail": "Rate limit exceeded. Please try again later."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Batch Operation Limits
|
||||||
|
|
||||||
|
For batch operations (`/v1/agent/batch/completions` and `/v1/swarm/batch/completions`):
|
||||||
|
|
||||||
|
- Maximum 10 concurrent requests per batch
|
||||||
|
|
||||||
|
- Exceeding this limit will result in a 400 (Bad Request) error
|
||||||
|
|
||||||
|
## Increasing Your Rate Limits
|
||||||
|
|
||||||
|
Need higher rate limits for your application? You can increase your limits by subscribing to a higher tier plan at [swarms.world/pricing](https://swarms.world/pricing).
|
||||||
|
|
||||||
|
Higher tier plans offer:
|
||||||
|
|
||||||
|
- Increased rate limits
|
||||||
|
|
||||||
|
- Higher batch operation limits
|
||||||
|
|
||||||
|
- Priority processing
|
||||||
|
|
||||||
|
- Dedicated support
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
To make the most of your rate limits:
|
||||||
|
|
||||||
|
1. Implement proper error handling for rate limit responses
|
||||||
|
|
||||||
|
2. Use batch operations when processing multiple requests
|
||||||
|
|
||||||
|
3. Add appropriate retry logic with exponential backoff
|
||||||
|
|
||||||
|
4. Monitor your API usage to stay within limits
|
||||||
|
|
||||||
|
## Rate Limit Headers
|
||||||
|
|
||||||
|
The API does not currently expose rate limit headers. We recommend implementing your own request tracking to stay within the limits.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
For questions about rate limits or to request a custom plan for higher limits, please contact our support team or visit [swarms.world/pricing](https://swarms.world/pricing).
|
@ -1,54 +1,30 @@
|
|||||||
### Available Swarms in The Swarms API
|
# Multi-Agent Architectures
|
||||||
|
|
||||||
| Swarm Type | Description (English) | Description (Chinese) |
|
Each multi-agent architecture type is designed for specific use cases and can be combined to create powerful multi-agent systems. Here's a comprehensive overview of each available swarm:
|
||||||
|----------------------|-----------------------------------------------------------------------------|----------------------------------------------------------------------------|
|
|
||||||
| AgentRearrange | A swarm type focused on rearranging agents for optimal performance. | 一种专注于重新排列代理以实现最佳性能的群类型。 |
|
|
||||||
| MixtureOfAgents | Combines different types of agents to achieve a specific goal. | 结合不同类型的代理以实现特定目标。 |
|
|
||||||
| SpreadSheetSwarm | Utilizes spreadsheet-like structures for data management and operations. | 利用类似电子表格的结构进行数据管理和操作。 |
|
|
||||||
| SequentialWorkflow | Executes tasks in a sequential manner. | 以顺序方式执行任务。 |
|
|
||||||
| ConcurrentWorkflow | Allows tasks to be executed concurrently for efficiency. | 允许任务并发执行以提高效率。 |
|
|
||||||
| GroupChat | Facilitates communication among agents in a group chat format. | 以群聊格式促进代理之间的沟通。 |
|
|
||||||
| MultiAgentRouter | Routes tasks and information among multiple agents. | 在多个代理之间路由任务和信息。 |
|
|
||||||
| AutoSwarmBuilder | Automatically builds and configures swarms based on predefined criteria. | 根据预定义标准自动构建和配置群。 |
|
|
||||||
| HiearchicalSwarm | Organizes agents in a hierarchical structure for task delegation. | 以层次结构组织代理以进行任务委派。 |
|
|
||||||
| auto | Automatically selects the best swarm type based on the context. | 根据上下文自动选择最佳群类型。 |
|
|
||||||
| MajorityVoting | Uses majority voting among agents to make decisions. | 使用代理之间的多数投票来做出决策。 |
|
|
||||||
| MALT | A specialized swarm type for specific tasks (details needed). | 一种专门为特定任务设计的群类型(需要详细信息)。 |
|
|
||||||
|
|
||||||
### Documentation for Swarms
|
| Swarm Type | Description | Learn More |
|
||||||
|
|---------------------|------------------------------------------------------------------------------|------------|
|
||||||
|
| AgentRearrange | Dynamically reorganizes agents to optimize task performance and efficiency. Optimizes agent performance by dynamically adjusting their roles and positions within the workflow. This architecture is particularly useful when the effectiveness of agents depends on their sequence or arrangement. | [Learn More](/swarms/structs/agent_rearrange) |
|
||||||
|
| MixtureOfAgents | Creates diverse teams of specialized agents, each bringing unique capabilities to solve complex problems. Each agent contributes unique skills to achieve the overall goal, making it excel at tasks requiring multiple types of expertise or processing. | [Learn More](/swarms/structs/moa) |
|
||||||
|
| SpreadSheetSwarm | Provides a structured approach to data management and operations, making it ideal for tasks involving data analysis, transformation, and systematic processing in a spreadsheet-like structure. | [Learn More](/swarms/structs/spreadsheet_swarm) |
|
||||||
|
| SequentialWorkflow | Ensures strict process control by executing tasks in a predefined order. Perfect for workflows where each step depends on the completion of previous steps. | [Learn More](/swarms/structs/sequential_workflow) |
|
||||||
|
| ConcurrentWorkflow | Maximizes efficiency by running independent tasks in parallel, significantly reducing overall processing time for complex operations. Ideal for independent tasks that can be processed simultaneously. | [Learn More](/swarms/structs/concurrentworkflow) |
|
||||||
|
| GroupChat | Enables dynamic collaboration between agents through a chat-based interface, facilitating real-time information sharing and decision-making. | [Learn More](/swarms/structs/group_chat) |
|
||||||
|
| MultiAgentRouter | Acts as an intelligent task dispatcher, ensuring optimal distribution of work across available agents based on their capabilities and current workload. | [Learn More](/swarms/structs/multi_agent_router) |
|
||||||
|
| AutoSwarmBuilder | Simplifies swarm creation by automatically configuring agent architectures based on task requirements and performance metrics. | [Learn More](/swarms/structs/auto_swarm_builder) |
|
||||||
|
| HiearchicalSwarm | Implements a structured approach to task management, with clear lines of authority and delegation across multiple agent levels. | [Learn More](/swarms/structs/multi_swarm_orchestration) |
|
||||||
|
| auto | Provides intelligent swarm selection based on context, automatically choosing the most effective architecture for given tasks. | [Learn More](/swarms/concept/how_to_choose_swarms) |
|
||||||
|
| MajorityVoting | Implements robust decision-making through consensus, particularly useful for tasks requiring collective intelligence or verification. | [Learn More](/swarms/structs/majorityvoting) |
|
||||||
|
| MALT | Specialized framework for language-based tasks, optimizing agent collaboration for complex language processing operations. | [Learn More](/swarms/structs/malt) |
|
||||||
|
|
||||||
1. **AgentRearrange**: This swarm type is designed to rearrange agents to optimize their performance in a given task. It is useful in scenarios where agent positioning or order affects the outcome.
|
# Learn More
|
||||||
- 这种群类型旨在重新排列代理以优化其在给定任务中的性能。它在代理位置或顺序影响结果的情况下非常有用。
|
|
||||||
|
|
||||||
2. **MixtureOfAgents**: This type combines various agents, each with unique capabilities, to work together towards a common goal. It leverages the strengths of different agents to enhance overall performance.
|
To learn more about Swarms architecture and how different swarm types work together, visit our comprehensive guides:
|
||||||
- 这种类型结合了各种代理,每个代理都有独特的能力,共同努力实现共同目标。它利用不同代理的优势来提高整体性能。
|
|
||||||
|
|
||||||
3. **SpreadSheetSwarm**: This swarm type uses spreadsheet-like structures to manage and operate on data. It is ideal for tasks that require organized data manipulation and analysis.
|
- [Introduction to Multi-Agent Architectures](/swarms/concept/swarm_architectures)
|
||||||
- 这种群类型使用类似电子表格的结构来管理和操作数据。它非常适合需要有组织的数据操作和分析的任务。
|
|
||||||
|
|
||||||
4. **SequentialWorkflow**: Tasks are executed one after another in this swarm type, ensuring that each step is completed before the next begins. It is suitable for processes that require strict order.
|
- [How to Choose the Right Multi-Agent Architecture](/swarms/concept/how_to_choose_swarms)
|
||||||
- 在这种群类型中,任务一个接一个地执行,确保每个步骤在下一个步骤开始之前完成。它适用于需要严格顺序的流程。
|
|
||||||
|
|
||||||
5. **ConcurrentWorkflow**: This type allows multiple tasks to be executed simultaneously, improving efficiency and reducing time for completion. It is best for independent tasks that do not rely on each other.
|
- [Framework Architecture Overview](/swarms/concept/framework_architecture)
|
||||||
- 这种类型允许多个任务同时执行,提高效率并减少完成时间。它最适合不相互依赖的独立任务。
|
|
||||||
|
|
||||||
6. **GroupChat**: Facilitates communication among agents in a group chat format, enabling real-time collaboration and decision-making.
|
- [Building Custom Swarms](/swarms/structs/custom_swarm)
|
||||||
- 以群聊格式促进代理之间的沟通,实现实时协作和决策。
|
|
||||||
|
|
||||||
7. **MultiAgentRouter**: This swarm type routes tasks and information among multiple agents, ensuring that each agent receives the necessary data to perform its function.
|
|
||||||
- 这种群类型在多个代理之间路由任务和信息,确保每个代理接收到执行其功能所需的数据。
|
|
||||||
|
|
||||||
8. **AutoSwarmBuilder**: Automatically builds and configures swarms based on predefined criteria, reducing the need for manual setup and configuration.
|
|
||||||
- 根据预定义标准自动构建和配置群,减少手动设置和配置的需要。
|
|
||||||
|
|
||||||
9. **HiearchicalSwarm**: Organizes agents in a hierarchical structure, allowing for efficient task delegation and management.
|
|
||||||
- 以层次结构组织代理,允许高效的任务委派和管理。
|
|
||||||
|
|
||||||
10. **auto**: Automatically selects the most appropriate swarm type based on the context and requirements of the task.
|
|
||||||
- 根据任务的上下文和要求自动选择最合适的群类型。
|
|
||||||
|
|
||||||
11. **MajorityVoting**: Uses a majority voting mechanism among agents to make decisions, ensuring that the most popular choice is selected.
|
|
||||||
- 使用代理之间的多数投票机制来做出决策,确保选择最受欢迎的选项。
|
|
||||||
|
|
||||||
12. **MALT**: A specialized swarm type designed for specific tasks. Further details are needed to fully document this type.
|
|
||||||
- 一种专门为特定任务设计的群类型。需要进一步的详细信息来完整记录这种类型。
|
|
||||||
|
@ -0,0 +1,163 @@
|
|||||||
|
"""
|
||||||
|
Medical Panel Discussion Example
|
||||||
|
|
||||||
|
This example demonstrates a panel of medical specialists discussing treatment solutions
|
||||||
|
for various diseases using InteractiveGroupChat with different speaker functions:
|
||||||
|
- Round Robin: Doctors speak in a fixed order
|
||||||
|
- Random: Doctors speak in random order
|
||||||
|
- Priority: Senior doctors speak first
|
||||||
|
- Custom: Disease-specific speaker function
|
||||||
|
|
||||||
|
The panel includes specialists from different medical fields who can collaborate
|
||||||
|
on complex medical cases and treatment plans.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.interactive_groupchat import (
|
||||||
|
InteractiveGroupChat,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_medical_panel():
|
||||||
|
"""Create a panel of medical specialists for discussion."""
|
||||||
|
|
||||||
|
# Cardiologist - Heart and cardiovascular system specialist
|
||||||
|
cardiologist = Agent(
|
||||||
|
agent_name="cardiologist",
|
||||||
|
system_prompt="""You are Dr. Sarah Chen, a board-certified cardiologist with 15 years of experience.
|
||||||
|
You specialize in cardiovascular diseases, heart failure, arrhythmias, and interventional cardiology.
|
||||||
|
You have expertise in:
|
||||||
|
- Coronary artery disease and heart attacks
|
||||||
|
- Heart failure and cardiomyopathy
|
||||||
|
- Arrhythmias and electrophysiology
|
||||||
|
- Hypertension and lipid disorders
|
||||||
|
- Cardiac imaging and diagnostic procedures
|
||||||
|
|
||||||
|
When discussing cases, provide evidence-based treatment recommendations,
|
||||||
|
consider patient risk factors, and collaborate with other specialists for comprehensive care.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Oncologist - Cancer specialist
|
||||||
|
oncologist = Agent(
|
||||||
|
agent_name="oncologist",
|
||||||
|
system_prompt="""You are Dr. Michael Rodriguez, a medical oncologist with 12 years of experience.
|
||||||
|
You specialize in the diagnosis and treatment of various types of cancer.
|
||||||
|
You have expertise in:
|
||||||
|
- Solid tumors (lung, breast, colon, prostate, etc.)
|
||||||
|
- Hematologic malignancies (leukemia, lymphoma, multiple myeloma)
|
||||||
|
- Targeted therapy and immunotherapy
|
||||||
|
- Clinical trials and novel treatments
|
||||||
|
- Palliative care and symptom management
|
||||||
|
|
||||||
|
When discussing cases, consider the cancer type, stage, molecular profile,
|
||||||
|
patient performance status, and available treatment options including clinical trials.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Neurologist - Nervous system specialist
|
||||||
|
neurologist = Agent(
|
||||||
|
agent_name="neurologist",
|
||||||
|
system_prompt="""You are Dr. Emily Watson, a neurologist with 10 years of experience.
|
||||||
|
You specialize in disorders of the nervous system, brain, and spinal cord.
|
||||||
|
You have expertise in:
|
||||||
|
- Stroke and cerebrovascular disease
|
||||||
|
- Neurodegenerative disorders (Alzheimer's, Parkinson's, ALS)
|
||||||
|
- Multiple sclerosis and demyelinating diseases
|
||||||
|
- Epilepsy and seizure disorders
|
||||||
|
- Headache and migraine disorders
|
||||||
|
- Neuromuscular diseases
|
||||||
|
|
||||||
|
When discussing cases, consider neurological symptoms, imaging findings,
|
||||||
|
and the impact of neurological conditions on overall patient care.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Endocrinologist - Hormone and metabolism specialist
|
||||||
|
endocrinologist = Agent(
|
||||||
|
agent_name="endocrinologist",
|
||||||
|
system_prompt="""You are Dr. James Thompson, an endocrinologist with 8 years of experience.
|
||||||
|
You specialize in disorders of the endocrine system and metabolism.
|
||||||
|
You have expertise in:
|
||||||
|
- Diabetes mellitus (Type 1, Type 2, gestational)
|
||||||
|
- Thyroid disorders (hyperthyroidism, hypothyroidism, thyroid cancer)
|
||||||
|
- Adrenal disorders and Cushing's syndrome
|
||||||
|
- Pituitary disorders and growth hormone issues
|
||||||
|
- Osteoporosis and calcium metabolism
|
||||||
|
- Reproductive endocrinology
|
||||||
|
|
||||||
|
When discussing cases, consider metabolic factors, hormone levels,
|
||||||
|
and how endocrine disorders may affect other organ systems.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Infectious Disease Specialist
|
||||||
|
infectious_disease = Agent(
|
||||||
|
agent_name="infectious_disease",
|
||||||
|
system_prompt="""You are Dr. Lisa Park, an infectious disease specialist with 11 years of experience.
|
||||||
|
You specialize in the diagnosis and treatment of infectious diseases.
|
||||||
|
You have expertise in:
|
||||||
|
- Bacterial, viral, fungal, and parasitic infections
|
||||||
|
- Antibiotic resistance and antimicrobial stewardship
|
||||||
|
- HIV/AIDS and opportunistic infections
|
||||||
|
- Travel medicine and tropical diseases
|
||||||
|
- Hospital-acquired infections
|
||||||
|
- Emerging infectious diseases
|
||||||
|
|
||||||
|
When discussing cases, consider the infectious agent, antimicrobial susceptibility,
|
||||||
|
host factors, and infection control measures.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return [
|
||||||
|
cardiologist,
|
||||||
|
oncologist,
|
||||||
|
neurologist,
|
||||||
|
endocrinologist,
|
||||||
|
infectious_disease,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def example_round_robin_panel():
|
||||||
|
"""Example with round robin speaking order."""
|
||||||
|
print("=== ROUND ROBIN MEDICAL PANEL ===\n")
|
||||||
|
|
||||||
|
agents = create_medical_panel()
|
||||||
|
|
||||||
|
group_chat = InteractiveGroupChat(
|
||||||
|
name="Medical Panel Discussion",
|
||||||
|
description="A collaborative panel of medical specialists discussing complex cases",
|
||||||
|
agents=agents,
|
||||||
|
speaker_function="round-robin-speaker",
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(group_chat.speaker_function)
|
||||||
|
|
||||||
|
# Case 1: Complex patient with multiple conditions
|
||||||
|
case1 = """CASE PRESENTATION:
|
||||||
|
A 65-year-old male with Type 2 diabetes, hypertension, and recent diagnosis of
|
||||||
|
stage 3 colon cancer presents with chest pain and shortness of breath.
|
||||||
|
ECG shows ST-segment elevation. Recent blood work shows elevated blood glucose (280 mg/dL)
|
||||||
|
and signs of infection (WBC 15,000, CRP elevated).
|
||||||
|
|
||||||
|
@cardiologist @oncologist @endocrinologist @infectious_disease please provide your
|
||||||
|
assessment and treatment recommendations for this complex case."""
|
||||||
|
|
||||||
|
response = group_chat.run(case1)
|
||||||
|
print(f"Response:\n{response}\n")
|
||||||
|
print("=" * 80 + "\n")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
example_round_robin_panel()
|
@ -0,0 +1,162 @@
|
|||||||
|
"""
|
||||||
|
Medical Panel Discussion Example
|
||||||
|
|
||||||
|
This example demonstrates a panel of medical specialists discussing treatment solutions
|
||||||
|
for various diseases using InteractiveGroupChat with different speaker functions:
|
||||||
|
- Round Robin: Doctors speak in a fixed order
|
||||||
|
- Random: Doctors speak in random order
|
||||||
|
- Priority: Senior doctors speak first
|
||||||
|
- Custom: Disease-specific speaker function
|
||||||
|
|
||||||
|
The panel includes specialists from different medical fields who can collaborate
|
||||||
|
on complex medical cases and treatment plans.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.interactive_groupchat import (
|
||||||
|
InteractiveGroupChat,
|
||||||
|
round_robin_speaker,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_medical_panel():
|
||||||
|
"""Create a panel of medical specialists for discussion."""
|
||||||
|
|
||||||
|
# Cardiologist - Heart and cardiovascular system specialist
|
||||||
|
cardiologist = Agent(
|
||||||
|
agent_name="cardiologist",
|
||||||
|
system_prompt="""You are Dr. Sarah Chen, a board-certified cardiologist with 15 years of experience.
|
||||||
|
You specialize in cardiovascular diseases, heart failure, arrhythmias, and interventional cardiology.
|
||||||
|
You have expertise in:
|
||||||
|
- Coronary artery disease and heart attacks
|
||||||
|
- Heart failure and cardiomyopathy
|
||||||
|
- Arrhythmias and electrophysiology
|
||||||
|
- Hypertension and lipid disorders
|
||||||
|
- Cardiac imaging and diagnostic procedures
|
||||||
|
|
||||||
|
When discussing cases, provide evidence-based treatment recommendations,
|
||||||
|
consider patient risk factors, and collaborate with other specialists for comprehensive care.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Oncologist - Cancer specialist
|
||||||
|
oncologist = Agent(
|
||||||
|
agent_name="oncologist",
|
||||||
|
system_prompt="""You are Dr. Michael Rodriguez, a medical oncologist with 12 years of experience.
|
||||||
|
You specialize in the diagnosis and treatment of various types of cancer.
|
||||||
|
You have expertise in:
|
||||||
|
- Solid tumors (lung, breast, colon, prostate, etc.)
|
||||||
|
- Hematologic malignancies (leukemia, lymphoma, multiple myeloma)
|
||||||
|
- Targeted therapy and immunotherapy
|
||||||
|
- Clinical trials and novel treatments
|
||||||
|
- Palliative care and symptom management
|
||||||
|
|
||||||
|
When discussing cases, consider the cancer type, stage, molecular profile,
|
||||||
|
patient performance status, and available treatment options including clinical trials.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Neurologist - Nervous system specialist
|
||||||
|
neurologist = Agent(
|
||||||
|
agent_name="neurologist",
|
||||||
|
system_prompt="""You are Dr. Emily Watson, a neurologist with 10 years of experience.
|
||||||
|
You specialize in disorders of the nervous system, brain, and spinal cord.
|
||||||
|
You have expertise in:
|
||||||
|
- Stroke and cerebrovascular disease
|
||||||
|
- Neurodegenerative disorders (Alzheimer's, Parkinson's, ALS)
|
||||||
|
- Multiple sclerosis and demyelinating diseases
|
||||||
|
- Epilepsy and seizure disorders
|
||||||
|
- Headache and migraine disorders
|
||||||
|
- Neuromuscular diseases
|
||||||
|
|
||||||
|
When discussing cases, consider neurological symptoms, imaging findings,
|
||||||
|
and the impact of neurological conditions on overall patient care.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Endocrinologist - Hormone and metabolism specialist
|
||||||
|
endocrinologist = Agent(
|
||||||
|
agent_name="endocrinologist",
|
||||||
|
system_prompt="""You are Dr. James Thompson, an endocrinologist with 8 years of experience.
|
||||||
|
You specialize in disorders of the endocrine system and metabolism.
|
||||||
|
You have expertise in:
|
||||||
|
- Diabetes mellitus (Type 1, Type 2, gestational)
|
||||||
|
- Thyroid disorders (hyperthyroidism, hypothyroidism, thyroid cancer)
|
||||||
|
- Adrenal disorders and Cushing's syndrome
|
||||||
|
- Pituitary disorders and growth hormone issues
|
||||||
|
- Osteoporosis and calcium metabolism
|
||||||
|
- Reproductive endocrinology
|
||||||
|
|
||||||
|
When discussing cases, consider metabolic factors, hormone levels,
|
||||||
|
and how endocrine disorders may affect other organ systems.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Infectious Disease Specialist
|
||||||
|
infectious_disease = Agent(
|
||||||
|
agent_name="infectious_disease",
|
||||||
|
system_prompt="""You are Dr. Lisa Park, an infectious disease specialist with 11 years of experience.
|
||||||
|
You specialize in the diagnosis and treatment of infectious diseases.
|
||||||
|
You have expertise in:
|
||||||
|
- Bacterial, viral, fungal, and parasitic infections
|
||||||
|
- Antibiotic resistance and antimicrobial stewardship
|
||||||
|
- HIV/AIDS and opportunistic infections
|
||||||
|
- Travel medicine and tropical diseases
|
||||||
|
- Hospital-acquired infections
|
||||||
|
- Emerging infectious diseases
|
||||||
|
|
||||||
|
When discussing cases, consider the infectious agent, antimicrobial susceptibility,
|
||||||
|
host factors, and infection control measures.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return [
|
||||||
|
cardiologist,
|
||||||
|
oncologist,
|
||||||
|
neurologist,
|
||||||
|
endocrinologist,
|
||||||
|
infectious_disease,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def example_round_robin_panel():
|
||||||
|
"""Example with round robin speaking order."""
|
||||||
|
print("=== ROUND ROBIN MEDICAL PANEL ===\n")
|
||||||
|
|
||||||
|
agents = create_medical_panel()
|
||||||
|
|
||||||
|
group_chat = InteractiveGroupChat(
|
||||||
|
name="Medical Panel Discussion",
|
||||||
|
description="A collaborative panel of medical specialists discussing complex cases",
|
||||||
|
agents=agents,
|
||||||
|
speaker_function=round_robin_speaker,
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Case 1: Complex patient with multiple conditions
|
||||||
|
case1 = """CASE PRESENTATION:
|
||||||
|
A 65-year-old male with Type 2 diabetes, hypertension, and recent diagnosis of
|
||||||
|
stage 3 colon cancer presents with chest pain and shortness of breath.
|
||||||
|
ECG shows ST-segment elevation. Recent blood work shows elevated blood glucose (280 mg/dL)
|
||||||
|
and signs of infection (WBC 15,000, CRP elevated).
|
||||||
|
|
||||||
|
@cardiologist @oncologist @endocrinologist @infectious_disease please provide your
|
||||||
|
assessment and treatment recommendations for this complex case."""
|
||||||
|
|
||||||
|
response = group_chat.run(case1)
|
||||||
|
print(f"Response:\n{response}\n")
|
||||||
|
print("=" * 80 + "\n")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
example_round_robin_panel()
|
@ -0,0 +1,162 @@
|
|||||||
|
"""
|
||||||
|
Medical Panel Discussion Example
|
||||||
|
|
||||||
|
This example demonstrates a panel of medical specialists discussing treatment solutions
|
||||||
|
for various diseases using InteractiveGroupChat with different speaker functions:
|
||||||
|
- Round Robin: Doctors speak in a fixed order
|
||||||
|
- Random: Doctors speak in random order
|
||||||
|
- Priority: Senior doctors speak first
|
||||||
|
- Custom: Disease-specific speaker function
|
||||||
|
|
||||||
|
The panel includes specialists from different medical fields who can collaborate
|
||||||
|
on complex medical cases and treatment plans.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from swarms import Agent
|
||||||
|
from swarms.structs.interactive_groupchat import (
|
||||||
|
InteractiveGroupChat,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_medical_panel():
|
||||||
|
"""Create a panel of medical specialists for discussion."""
|
||||||
|
|
||||||
|
# Cardiologist - Heart and cardiovascular system specialist
|
||||||
|
cardiologist = Agent(
|
||||||
|
agent_name="cardiologist",
|
||||||
|
system_prompt="""You are Dr. Sarah Chen, a board-certified cardiologist with 15 years of experience.
|
||||||
|
You specialize in cardiovascular diseases, heart failure, arrhythmias, and interventional cardiology.
|
||||||
|
You have expertise in:
|
||||||
|
- Coronary artery disease and heart attacks
|
||||||
|
- Heart failure and cardiomyopathy
|
||||||
|
- Arrhythmias and electrophysiology
|
||||||
|
- Hypertension and lipid disorders
|
||||||
|
- Cardiac imaging and diagnostic procedures
|
||||||
|
|
||||||
|
When discussing cases, provide evidence-based treatment recommendations,
|
||||||
|
consider patient risk factors, and collaborate with other specialists for comprehensive care.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Oncologist - Cancer specialist
|
||||||
|
oncologist = Agent(
|
||||||
|
agent_name="oncologist",
|
||||||
|
system_prompt="""You are Dr. Michael Rodriguez, a medical oncologist with 12 years of experience.
|
||||||
|
You specialize in the diagnosis and treatment of various types of cancer.
|
||||||
|
You have expertise in:
|
||||||
|
- Solid tumors (lung, breast, colon, prostate, etc.)
|
||||||
|
- Hematologic malignancies (leukemia, lymphoma, multiple myeloma)
|
||||||
|
- Targeted therapy and immunotherapy
|
||||||
|
- Clinical trials and novel treatments
|
||||||
|
- Palliative care and symptom management
|
||||||
|
|
||||||
|
When discussing cases, consider the cancer type, stage, molecular profile,
|
||||||
|
patient performance status, and available treatment options including clinical trials.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Neurologist - Nervous system specialist
|
||||||
|
neurologist = Agent(
|
||||||
|
agent_name="neurologist",
|
||||||
|
system_prompt="""You are Dr. Emily Watson, a neurologist with 10 years of experience.
|
||||||
|
You specialize in disorders of the nervous system, brain, and spinal cord.
|
||||||
|
You have expertise in:
|
||||||
|
- Stroke and cerebrovascular disease
|
||||||
|
- Neurodegenerative disorders (Alzheimer's, Parkinson's, ALS)
|
||||||
|
- Multiple sclerosis and demyelinating diseases
|
||||||
|
- Epilepsy and seizure disorders
|
||||||
|
- Headache and migraine disorders
|
||||||
|
- Neuromuscular diseases
|
||||||
|
|
||||||
|
When discussing cases, consider neurological symptoms, imaging findings,
|
||||||
|
and the impact of neurological conditions on overall patient care.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Endocrinologist - Hormone and metabolism specialist
|
||||||
|
endocrinologist = Agent(
|
||||||
|
agent_name="endocrinologist",
|
||||||
|
system_prompt="""You are Dr. James Thompson, an endocrinologist with 8 years of experience.
|
||||||
|
You specialize in disorders of the endocrine system and metabolism.
|
||||||
|
You have expertise in:
|
||||||
|
- Diabetes mellitus (Type 1, Type 2, gestational)
|
||||||
|
- Thyroid disorders (hyperthyroidism, hypothyroidism, thyroid cancer)
|
||||||
|
- Adrenal disorders and Cushing's syndrome
|
||||||
|
- Pituitary disorders and growth hormone issues
|
||||||
|
- Osteoporosis and calcium metabolism
|
||||||
|
- Reproductive endocrinology
|
||||||
|
|
||||||
|
When discussing cases, consider metabolic factors, hormone levels,
|
||||||
|
and how endocrine disorders may affect other organ systems.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Infectious Disease Specialist
|
||||||
|
infectious_disease = Agent(
|
||||||
|
agent_name="infectious_disease",
|
||||||
|
system_prompt="""You are Dr. Lisa Park, an infectious disease specialist with 11 years of experience.
|
||||||
|
You specialize in the diagnosis and treatment of infectious diseases.
|
||||||
|
You have expertise in:
|
||||||
|
- Bacterial, viral, fungal, and parasitic infections
|
||||||
|
- Antibiotic resistance and antimicrobial stewardship
|
||||||
|
- HIV/AIDS and opportunistic infections
|
||||||
|
- Travel medicine and tropical diseases
|
||||||
|
- Hospital-acquired infections
|
||||||
|
- Emerging infectious diseases
|
||||||
|
|
||||||
|
When discussing cases, consider the infectious agent, antimicrobial susceptibility,
|
||||||
|
host factors, and infection control measures.""",
|
||||||
|
model_name="claude-3-5-sonnet-20240620",
|
||||||
|
streaming_on=True,
|
||||||
|
print_on=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return [
|
||||||
|
cardiologist,
|
||||||
|
oncologist,
|
||||||
|
neurologist,
|
||||||
|
endocrinologist,
|
||||||
|
infectious_disease,
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def example_round_robin_panel():
|
||||||
|
"""Example with round robin speaking order."""
|
||||||
|
print("=== ROUND ROBIN MEDICAL PANEL ===\n")
|
||||||
|
|
||||||
|
agents = create_medical_panel()
|
||||||
|
|
||||||
|
group_chat = InteractiveGroupChat(
|
||||||
|
name="Medical Panel Discussion",
|
||||||
|
description="A collaborative panel of medical specialists discussing complex cases",
|
||||||
|
agents=agents,
|
||||||
|
speaker_function="random-dynamic-speaker",
|
||||||
|
interactive=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(group_chat.speaker_function)
|
||||||
|
print(group_chat.get_current_speaker_function())
|
||||||
|
|
||||||
|
# Case 1: Complex patient with multiple conditions
|
||||||
|
case1 = """CASE PRESENTATION:
|
||||||
|
A 65-year-old male with Type 2 diabetes, hypertension, and recent diagnosis of
|
||||||
|
stage 3 colon cancer presents with chest pain and shortness of breath.
|
||||||
|
ECG shows ST-segment elevation. Recent blood work shows elevated blood glucose (280 mg/dL)
|
||||||
|
and signs of infection (WBC 15,000, CRP elevated).
|
||||||
|
|
||||||
|
@cardiologist @oncologist @endocrinologist @infectious_disease please provide your
|
||||||
|
assessment and treatment recommendations for this complex case."""
|
||||||
|
|
||||||
|
group_chat.run(case1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
example_round_robin_panel()
|
Loading…
Reference in new issue