|
1 | | -# AgentRegistry Documentation |
| 1 | +# AgentRegistry |
2 | 2 |
|
3 | | -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. |
| 3 | +`AgentRegistry` manages a collection of `Agent` instances keyed by each agent's |
| 4 | +`agent_name`. Use it when an application needs to add, retrieve, update, delete, |
| 5 | +or query agents at runtime while keeping registry operations thread-safe. |
4 | 6 |
|
5 | | -## Attributes |
| 7 | +The registry stores the live `Agent` objects in `self.agents` and records |
| 8 | +metadata for each registered agent in `AgentRegistrySchema` through |
| 9 | +`AgentConfigSchema`. |
6 | 10 |
|
7 | | -### AgentModel |
8 | | - |
9 | | -| Attribute | Type | Description | |
10 | | -|-----------|--------|--------------------------------------| |
11 | | -| `agent_id`| `str` | The unique identifier for the agent. | |
12 | | -| `agent` | `Agent`| The agent object. | |
13 | | - |
14 | | -### AgentRegistry |
15 | | - |
16 | | -| Attribute | Type | Description | |
17 | | -|-----------|---------------------|-------------------------------------------| |
18 | | -| `agents` | `Dict[str, AgentModel]` | A dictionary mapping agent IDs to `AgentModel` instances. | |
19 | | -| `lock` | `Lock` | A threading lock for thread-safe operations. | |
20 | | - |
21 | | -## Methods |
22 | | - |
23 | | -### `__init__(self)` |
24 | | - |
25 | | -Initializes the `AgentRegistry` object. |
26 | | - |
27 | | -- **Usage Example:** |
28 | | - ```python |
29 | | - registry = AgentRegistry() |
30 | | - ``` |
31 | | - |
32 | | -### `add(self, agent_id: str, agent: Agent) -> None` |
33 | | - |
34 | | -Adds a new agent to the registry. |
35 | | - |
36 | | -- **Parameters:** |
37 | | - - `agent_id` (`str`): The unique identifier for the agent. |
38 | | - - `agent` (`Agent`): The agent to add. |
39 | | - |
40 | | -- **Raises:** |
41 | | - - `ValueError`: If the agent ID already exists in the registry. |
42 | | - - `ValidationError`: If the input data is invalid. |
43 | | - |
44 | | -- **Usage Example:** |
45 | | - ```python |
46 | | - agent = Agent(agent_name="Agent1") |
47 | | - registry.add("agent_1", agent) |
48 | | - ``` |
49 | | - |
50 | | -### `delete(self, agent_id: str) -> None` |
51 | | - |
52 | | -Deletes an agent from the registry. |
53 | | - |
54 | | -- **Parameters:** |
55 | | - - `agent_id` (`str`): The unique identifier for the agent to delete. |
56 | | - |
57 | | -- **Raises:** |
58 | | - - `KeyError`: If the agent ID does not exist in the registry. |
59 | | - |
60 | | -- **Usage Example:** |
61 | | - ```python |
62 | | - registry.delete("agent_1") |
63 | | - ``` |
64 | | - |
65 | | -### `update_agent(self, agent_id: str, new_agent: Agent) -> None` |
66 | | - |
67 | | -Updates an existing agent in the registry. |
68 | | - |
69 | | -- **Parameters:** |
70 | | - - `agent_id` (`str`): The unique identifier for the agent to update. |
71 | | - - `new_agent` (`Agent`): The new agent to replace the existing one. |
72 | | - |
73 | | -- **Raises:** |
74 | | - - `KeyError`: If the agent ID does not exist in the registry. |
75 | | - - `ValidationError`: If the input data is invalid. |
76 | | - |
77 | | -- **Usage Example:** |
78 | | - ```python |
79 | | - new_agent = Agent(agent_name="UpdatedAgent") |
80 | | - registry.update_agent("agent_1", new_agent) |
81 | | - ``` |
82 | | - |
83 | | -### `get(self, agent_id: str) -> Agent` |
84 | | - |
85 | | -Retrieves an agent from the registry. |
86 | | - |
87 | | -- **Parameters:** |
88 | | - - `agent_id` (`str`): The unique identifier for the agent to retrieve. |
89 | | - |
90 | | -- **Returns:** |
91 | | - - `Agent`: The agent associated with the given agent ID. |
92 | | - |
93 | | -- **Raises:** |
94 | | - - `KeyError`: If the agent ID does not exist in the registry. |
95 | | - |
96 | | -- **Usage Example:** |
97 | | - ```python |
98 | | - agent = registry.get("agent_1") |
99 | | - ``` |
100 | | - |
101 | | -### `list_agents(self) -> List[str]` |
102 | | - |
103 | | -Lists all agent identifiers in the registry. |
104 | | - |
105 | | -- **Returns:** |
106 | | - - `List[str]`: A list of all agent identifiers. |
107 | | - |
108 | | -- **Usage Example:** |
109 | | - ```python |
110 | | - agent_ids = registry.list_agents() |
111 | | - ``` |
112 | | - |
113 | | -### `query(self, condition: Optional[Callable[[Agent], bool]] = None) -> List[Agent]` |
114 | | - |
115 | | -Queries agents based on a condition. |
116 | | - |
117 | | -- **Parameters:** |
118 | | - - `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`. |
119 | | - |
120 | | -- **Returns:** |
121 | | - - `List[Agent]`: A list of agents that meet the condition. |
122 | | - |
123 | | -- **Usage Example:** |
124 | | - ```python |
125 | | - def is_active(agent): |
126 | | - return agent.is_active |
127 | | - |
128 | | - active_agents = registry.query(is_active) |
129 | | - ``` |
130 | | - |
131 | | -### `find_agent_by_name(self, agent_name: str) -> Agent` |
132 | | - |
133 | | -Finds an agent by its name. |
134 | | - |
135 | | -- **Parameters:** |
136 | | - - `agent_name` (`str`): The name of the agent to find. |
137 | | - |
138 | | -- **Returns:** |
139 | | - - `Agent`: The agent with the specified name. |
140 | | - |
141 | | -- **Usage Example:** |
142 | | - ```python |
143 | | - agent = registry.find_agent_by_name("Agent1") |
144 | | - ``` |
145 | | - |
146 | | - |
147 | | -### Full Example |
| 11 | +## Quick Start |
148 | 12 |
|
149 | 13 | ```python |
| 14 | +from swarms import Agent |
150 | 15 | from swarms.structs.agent_registry import AgentRegistry |
151 | | -from swarms import Agent, OpenAIChat, Anthropic |
152 | | - |
153 | | -# Initialize the agents |
154 | | -growth_agent1 = Agent( |
155 | | - agent_name="Marketing Specialist", |
156 | | - system_prompt="You're the marketing specialist, your purpose is to help companies grow by improving their marketing strategies!", |
157 | | - agent_description="Improve a company's marketing strategies!", |
158 | | - llm=OpenAIChat(), |
159 | | - max_loops="auto", |
160 | | - autosave=True, |
161 | | - dashboard=False, |
162 | | - verbose=True, |
163 | | - streaming_on=True, |
164 | | - saved_state_path="marketing_specialist.json", |
165 | | - stopping_token="Stop!", |
166 | | - interactive=True, |
167 | | - context_length=1000, |
168 | | -) |
169 | 16 |
|
170 | | -growth_agent2 = Agent( |
171 | | - agent_name="Sales Specialist", |
172 | | - system_prompt="You're the sales specialist, your purpose is to help companies grow by improving their sales strategies!", |
173 | | - agent_description="Improve a company's sales strategies!", |
174 | | - llm=Anthropic(), |
175 | | - max_loops="auto", |
176 | | - autosave=True, |
177 | | - dashboard=False, |
178 | | - verbose=True, |
179 | | - streaming_on=True, |
180 | | - saved_state_path="sales_specialist.json", |
181 | | - stopping_token="Stop!", |
182 | | - interactive=True, |
183 | | - context_length=1000, |
184 | | -) |
| 17 | +researcher = Agent(agent_name="Researcher") |
| 18 | +writer = Agent(agent_name="Writer") |
185 | 19 |
|
186 | | -growth_agent3 = Agent( |
187 | | - agent_name="Product Development Specialist", |
188 | | - system_prompt="You're the product development specialist, your purpose is to help companies grow by improving their product development strategies!", |
189 | | - agent_description="Improve a company's product development strategies!", |
190 | | - llm=Anthropic(), |
191 | | - max_loops="auto", |
192 | | - autosave=True, |
193 | | - dashboard=False, |
194 | | - verbose=True, |
195 | | - streaming_on=True, |
196 | | - saved_state_path="product_development_specialist.json", |
197 | | - stopping_token="Stop!", |
198 | | - interactive=True, |
199 | | - context_length=1000, |
| 20 | +registry = AgentRegistry( |
| 21 | + name="Content Team", |
| 22 | + description="Agents used in the content workflow.", |
| 23 | + agents=[researcher], |
200 | 24 | ) |
201 | 25 |
|
202 | | -growth_agent4 = Agent( |
203 | | - agent_name="Customer Service Specialist", |
204 | | - system_prompt="You're the customer service specialist, your purpose is to help companies grow by improving their customer service strategies!", |
205 | | - agent_description="Improve a company's customer service strategies!", |
206 | | - llm=OpenAIChat(), |
207 | | - max_loops="auto", |
208 | | - autosave=True, |
209 | | - dashboard=False, |
210 | | - verbose=True, |
211 | | - streaming_on=True, |
212 | | - saved_state_path="customer_service_specialist.json", |
213 | | - stopping_token="Stop!", |
214 | | - interactive=True, |
215 | | - context_length=1000, |
216 | | -) |
| 26 | +registry.add(writer) |
217 | 27 |
|
| 28 | +print(registry.list_agents()) |
| 29 | +# ["Researcher", "Writer"] |
218 | 30 |
|
219 | | -# Register the agents\ |
220 | | -registry = AgentRegistry() |
221 | | - |
222 | | -# Register the agents |
223 | | -registry.add("Marketing Specialist", growth_agent1) |
224 | | -registry.add("Sales Specialist", growth_agent2) |
225 | | -registry.add("Product Development Specialist", growth_agent3) |
226 | | -registry.add("Customer Service Specialist", growth_agent4) |
| 31 | +writer_agent = registry.get("Writer") |
| 32 | +matching_agents = registry.query( |
| 33 | + lambda agent: agent.agent_name.endswith("er") |
| 34 | +) |
227 | 35 |
|
| 36 | +updated_writer = Agent(agent_name="Writer") |
| 37 | +registry.update_agent("Writer", updated_writer) |
| 38 | +registry.delete("Researcher") |
228 | 39 | ``` |
229 | 40 |
|
230 | | -## Logging and Error Handling |
| 41 | +## Constructor |
231 | 42 |
|
232 | | -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. |
| 43 | +```python |
| 44 | +AgentRegistry( |
| 45 | + name="Agent Registry", |
| 46 | + description="A registry for managing agents.", |
| 47 | + agents=None, |
| 48 | + return_json=True, |
| 49 | + auto_save=False, |
| 50 | +) |
| 51 | +``` |
233 | 52 |
|
234 | | -## Additional Tips |
| 53 | +| Parameter | Type | Description | |
| 54 | +|-----------|------|-------------| |
| 55 | +| `name` | `str` | Human-readable registry name. | |
| 56 | +| `description` | `str` | Human-readable registry description. | |
| 57 | +| `agents` | `Optional[List[Agent]]` | Agents to register during initialization. | |
| 58 | +| `return_json` | `bool` | Stores whether callers expect JSON output. | |
| 59 | +| `auto_save` | `bool` | Stores whether automatic persistence should be enabled. | |
235 | 60 |
|
236 | | -- Ensure that agents provided to the `AgentRegistry` are properly initialized and configured to handle the tasks they will receive. |
237 | | -- Utilize the logging information to monitor and debug the registry operations. |
238 | | -- Use the `lock` attribute to ensure thread-safe operations when accessing or modifying the registry. |
| 61 | +## Methods |
239 | 62 |
|
| 63 | +| Method | Description | |
| 64 | +|--------|-------------| |
| 65 | +| `add(agent)` | Adds an `Agent` using `agent.agent_name` as the registry key. Raises `ValueError` when that name already exists. | |
| 66 | +| `add_many(agents)` | Adds a list of agents concurrently through `add`. | |
| 67 | +| `delete(agent_name)` | Removes an agent by name. Raises `KeyError` when the name is missing. | |
| 68 | +| `update_agent(agent_name, new_agent)` | Replaces the agent stored under `agent_name`. Raises `KeyError` when the name is missing. | |
| 69 | +| `get(agent_name)` | Returns the agent stored under `agent_name`. Raises `KeyError` when the name is missing. | |
| 70 | +| `list_agents()` | Returns all registered agent names. | |
| 71 | +| `return_all_agents()` | Returns all registered `Agent` objects. | |
| 72 | +| `query(condition=None)` | Returns all agents when `condition` is `None`; otherwise returns agents where `condition(agent)` is true. | |
| 73 | +| `find_agent_by_name(agent_name)` | Searches the registry and returns the matching agent, or `None` when no match is found. | |
| 74 | +| `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. | |
| 75 | +| `agents_to_json()` | Serializes registered agents to a JSON string keyed by agent name. | |
| 76 | +| `agent_to_py_model(agent)` | Converts an agent into `AgentConfigSchema` metadata and appends it to the registry schema. | |
| 77 | + |
| 78 | +## Data Model |
| 79 | + |
| 80 | +`AgentConfigSchema` stores metadata for each registered agent: |
| 81 | + |
| 82 | +| Field | Type | Description | |
| 83 | +|-------|------|-------------| |
| 84 | +| `uuid` | `str` | Agent identifier from `agent.id`. | |
| 85 | +| `name` | `str` | Agent name from `agent.agent_name`. | |
| 86 | +| `description` | `str` | Agent description, or a default value when none is set. | |
| 87 | +| `time_added` | `str` | UTC timestamp captured when the schema entry is created. | |
| 88 | +| `config` | `Dict[Any, Any]` | Agent configuration from `agent.to_dict()`. | |
| 89 | + |
| 90 | +`AgentRegistrySchema` stores registry-level metadata, including the registry |
| 91 | +name, description, schema entries, creation timestamp, and number of agents. |
| 92 | + |
| 93 | +## Usage Notes |
| 94 | + |
| 95 | +- Agent names must be unique inside a registry because `agent.agent_name` is the |
| 96 | + storage key. |
| 97 | +- `get`, `delete`, and `update_agent` raise `KeyError` for missing names. |
| 98 | +- `add` raises `ValueError` for duplicate names. |
| 99 | +- Use `query` for custom filtering without copying registry state manually. |
| 100 | +- Use `agents_to_json` when a JSON snapshot of the registered agents is needed. |
0 commit comments