Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/.readthedocs.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
version: 2

build:
os: ubuntu-24.04
tools:
python: "3.12"

mkdocs:
configuration: docs/mkdocs.yml

python:
install:
- requirements: docs/requirements.txt
18 changes: 18 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Swarms Documentation

Swarms is a production-oriented framework for building, orchestrating,
and evaluating single-agent and multi-agent systems.

## Start Here

- [Installation](swarms/install/install.md)
- [Environment Configuration](swarms/install/env.md)
- [Agents](swarms/agents/index.md)
- [Multi-Agent Architectures](swarms/structs/index.md)

## Core References

- [Agent API](swarms/structs/agent.md)
- [Swarm Router](swarms/structs/swarm_router.md)
- [Tools and MCP](swarms/tools/tools_examples.md)
- [Examples](swarms/examples/basic_agent.md)
1 change: 0 additions & 1 deletion docs/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,6 @@ extra:

theme:
name: material
custom_dir: overrides
logo: assets/img/swarms-logo.png
palette:
- scheme: default
Expand Down
8 changes: 8 additions & 0 deletions docs/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
mkdocs<1.6
mkdocs-material
mkdocs-git-authors-plugin
mkdocs-jupyter==0.16.0
lxml_html_clean
mkdocstrings[python]
mkdocs-git-committers-plugin
mkdocs-git-revision-date-localized-plugin
301 changes: 81 additions & 220 deletions docs/swarms/structs/agent_registry.md
Original file line number Diff line number Diff line change
@@ -1,239 +1,100 @@
# AgentRegistry Documentation
# AgentRegistry

The `AgentRegistry` class is designed to manage a collection of agents, providing methods for adding, deleting, updating, and querying agents. This class ensures thread-safe operations on the registry, making it suitable for concurrent environments. Additionally, the `AgentModel` class is a Pydantic model used for validating and storing agent information.
`AgentRegistry` manages a collection of `Agent` instances keyed by each agent's
`agent_name`. Use it when an application needs to add, retrieve, update, delete,
or query agents at runtime while keeping registry operations thread-safe.

## Attributes
The registry stores the live `Agent` objects in `self.agents` and records
metadata for each registered agent in `AgentRegistrySchema` through
`AgentConfigSchema`.

### AgentModel

| Attribute | Type | Description |
|-----------|--------|--------------------------------------|
| `agent_id`| `str` | The unique identifier for the agent. |
| `agent` | `Agent`| The agent object. |

### AgentRegistry

| Attribute | Type | Description |
|-----------|---------------------|-------------------------------------------|
| `agents` | `Dict[str, AgentModel]` | A dictionary mapping agent IDs to `AgentModel` instances. |
| `lock` | `Lock` | A threading lock for thread-safe operations. |

## Methods

### `__init__(self)`

Initializes the `AgentRegistry` object.

- **Usage Example:**
```python
registry = AgentRegistry()
```

### `add(self, agent_id: str, agent: Agent) -> None`

Adds a new agent to the registry.

- **Parameters:**
- `agent_id` (`str`): The unique identifier for the agent.
- `agent` (`Agent`): The agent to add.

- **Raises:**
- `ValueError`: If the agent ID already exists in the registry.
- `ValidationError`: If the input data is invalid.

- **Usage Example:**
```python
agent = Agent(agent_name="Agent1")
registry.add("agent_1", agent)
```

### `delete(self, agent_id: str) -> None`

Deletes an agent from the registry.

- **Parameters:**
- `agent_id` (`str`): The unique identifier for the agent to delete.

- **Raises:**
- `KeyError`: If the agent ID does not exist in the registry.

- **Usage Example:**
```python
registry.delete("agent_1")
```

### `update_agent(self, agent_id: str, new_agent: Agent) -> None`

Updates an existing agent in the registry.

- **Parameters:**
- `agent_id` (`str`): The unique identifier for the agent to update.
- `new_agent` (`Agent`): The new agent to replace the existing one.

- **Raises:**
- `KeyError`: If the agent ID does not exist in the registry.
- `ValidationError`: If the input data is invalid.

- **Usage Example:**
```python
new_agent = Agent(agent_name="UpdatedAgent")
registry.update_agent("agent_1", new_agent)
```

### `get(self, agent_id: str) -> Agent`

Retrieves an agent from the registry.

- **Parameters:**
- `agent_id` (`str`): The unique identifier for the agent to retrieve.

- **Returns:**
- `Agent`: The agent associated with the given agent ID.

- **Raises:**
- `KeyError`: If the agent ID does not exist in the registry.

- **Usage Example:**
```python
agent = registry.get("agent_1")
```

### `list_agents(self) -> List[str]`

Lists all agent identifiers in the registry.

- **Returns:**
- `List[str]`: A list of all agent identifiers.

- **Usage Example:**
```python
agent_ids = registry.list_agents()
```

### `query(self, condition: Optional[Callable[[Agent], bool]] = None) -> List[Agent]`

Queries agents based on a condition.

- **Parameters:**
- `condition` (`Optional[Callable[[Agent], bool]]`): A function that takes an agent and returns a boolean indicating whether the agent meets the condition. Defaults to `None`.

- **Returns:**
- `List[Agent]`: A list of agents that meet the condition.

- **Usage Example:**
```python
def is_active(agent):
return agent.is_active

active_agents = registry.query(is_active)
```

### `find_agent_by_name(self, agent_name: str) -> Agent`

Finds an agent by its name.

- **Parameters:**
- `agent_name` (`str`): The name of the agent to find.

- **Returns:**
- `Agent`: The agent with the specified name.

- **Usage Example:**
```python
agent = registry.find_agent_by_name("Agent1")
```


### Full Example
## Quick Start

```python
from swarms import Agent
from swarms.structs.agent_registry import AgentRegistry
from swarms import Agent, OpenAIChat, Anthropic

# Initialize the agents
growth_agent1 = Agent(
agent_name="Marketing Specialist",
system_prompt="You're the marketing specialist, your purpose is to help companies grow by improving their marketing strategies!",
agent_description="Improve a company's marketing strategies!",
llm=OpenAIChat(),
max_loops="auto",
autosave=True,
dashboard=False,
verbose=True,
streaming_on=True,
saved_state_path="marketing_specialist.json",
stopping_token="Stop!",
interactive=True,
context_length=1000,
)

growth_agent2 = Agent(
agent_name="Sales Specialist",
system_prompt="You're the sales specialist, your purpose is to help companies grow by improving their sales strategies!",
agent_description="Improve a company's sales strategies!",
llm=Anthropic(),
max_loops="auto",
autosave=True,
dashboard=False,
verbose=True,
streaming_on=True,
saved_state_path="sales_specialist.json",
stopping_token="Stop!",
interactive=True,
context_length=1000,
)
researcher = Agent(agent_name="Researcher")
writer = Agent(agent_name="Writer")

growth_agent3 = Agent(
agent_name="Product Development Specialist",
system_prompt="You're the product development specialist, your purpose is to help companies grow by improving their product development strategies!",
agent_description="Improve a company's product development strategies!",
llm=Anthropic(),
max_loops="auto",
autosave=True,
dashboard=False,
verbose=True,
streaming_on=True,
saved_state_path="product_development_specialist.json",
stopping_token="Stop!",
interactive=True,
context_length=1000,
registry = AgentRegistry(
name="Content Team",
description="Agents used in the content workflow.",
agents=[researcher],
)

growth_agent4 = Agent(
agent_name="Customer Service Specialist",
system_prompt="You're the customer service specialist, your purpose is to help companies grow by improving their customer service strategies!",
agent_description="Improve a company's customer service strategies!",
llm=OpenAIChat(),
max_loops="auto",
autosave=True,
dashboard=False,
verbose=True,
streaming_on=True,
saved_state_path="customer_service_specialist.json",
stopping_token="Stop!",
interactive=True,
context_length=1000,
)
registry.add(writer)

print(registry.list_agents())
# ["Researcher", "Writer"]

# Register the agents\
registry = AgentRegistry()

# Register the agents
registry.add("Marketing Specialist", growth_agent1)
registry.add("Sales Specialist", growth_agent2)
registry.add("Product Development Specialist", growth_agent3)
registry.add("Customer Service Specialist", growth_agent4)
writer_agent = registry.get("Writer")
matching_agents = registry.query(
lambda agent: agent.agent_name.endswith("er")
)

updated_writer = Agent(agent_name="Writer")
registry.update_agent("Writer", updated_writer)
registry.delete("Researcher")
```

## Logging and Error Handling
## Constructor

Each method in the `AgentRegistry` class includes logging to track the execution flow and captures errors to provide detailed information in case of failures. This is crucial for debugging and ensuring smooth operation of the registry. The `report_error` function is used for reporting exceptions that occur during method execution.
```python
AgentRegistry(
name="Agent Registry",
description="A registry for managing agents.",
agents=None,
return_json=True,
auto_save=False,
)
```

## Additional Tips
| Parameter | Type | Description |
|-----------|------|-------------|
| `name` | `str` | Human-readable registry name. |
| `description` | `str` | Human-readable registry description. |
| `agents` | `Optional[List[Agent]]` | Agents to register during initialization. |
| `return_json` | `bool` | Stores whether callers expect JSON output. |
| `auto_save` | `bool` | Stores whether automatic persistence should be enabled. |

- Ensure that agents provided to the `AgentRegistry` are properly initialized and configured to handle the tasks they will receive.
- Utilize the logging information to monitor and debug the registry operations.
- Use the `lock` attribute to ensure thread-safe operations when accessing or modifying the registry.
## Methods

| Method | Description |
|--------|-------------|
| `add(agent)` | Adds an `Agent` using `agent.agent_name` as the registry key. Raises `ValueError` when that name already exists. |
| `add_many(agents)` | Adds a list of agents concurrently through `add`. |
| `delete(agent_name)` | Removes an agent by name. Raises `KeyError` when the name is missing. |
| `update_agent(agent_name, new_agent)` | Replaces the agent stored under `agent_name`. Raises `KeyError` when the name is missing. |
| `get(agent_name)` | Returns the agent stored under `agent_name`. Raises `KeyError` when the name is missing. |
| `list_agents()` | Returns all registered agent names. |
| `return_all_agents()` | Returns all registered `Agent` objects. |
| `query(condition=None)` | Returns all agents when `condition` is `None`; otherwise returns agents where `condition(agent)` is true. |
| `find_agent_by_name(agent_name)` | Searches the registry and returns the matching agent, or `None` when no match is found. |
| `find_agent_by_id(agent_id)` | Performs a direct dictionary lookup with the provided key. Since `add` stores agents by `agent_name`, prefer `get` or `find_agent_by_name` for normal lookups. |
| `agents_to_json()` | Serializes registered agents to a JSON string keyed by agent name. |
| `agent_to_py_model(agent)` | Converts an agent into `AgentConfigSchema` metadata and appends it to the registry schema. |

## Data Model

`AgentConfigSchema` stores metadata for each registered agent:

| Field | Type | Description |
|-------|------|-------------|
| `uuid` | `str` | Agent identifier from `agent.id`. |
| `name` | `str` | Agent name from `agent.agent_name`. |
| `description` | `str` | Agent description, or a default value when none is set. |
| `time_added` | `str` | UTC timestamp captured when the schema entry is created. |
| `config` | `Dict[Any, Any]` | Agent configuration from `agent.to_dict()`. |

`AgentRegistrySchema` stores registry-level metadata, including the registry
name, description, schema entries, creation timestamp, and number of agents.

## Usage Notes

- Agent names must be unique inside a registry because `agent.agent_name` is the
storage key.
- `get`, `delete`, and `update_agent` raise `KeyError` for missing names.
- `add` raises `ValueError` for duplicate names.
- Use `query` for custom filtering without copying registry state manually.
- Use `agents_to_json` when a JSON snapshot of the registered agents is needed.