Protocols API¶
SubAgentDepsProtocol¶
subagents_pydantic_ai.SubAgentDepsProtocol
¶
Bases: Protocol
Protocol for dependencies that support subagent management.
Any deps class that wants to use the subagent toolset must implement
this protocol. The key requirement is a subagents dict for storing
compiled agent instances and a clone_for_subagent method for creating
isolated deps for nested subagents.
Example
Source code in src/subagents_pydantic_ai/protocols.py
clone_for_subagent(max_depth=0)
¶
Create a new deps instance for a subagent.
Subagents typically get: - Shared resources (backend, files, etc.) - Empty or limited subagents dict (based on max_depth) - Fresh state for task-specific data
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_depth
|
int
|
Maximum nesting depth for the subagent. If 0, the subagent cannot spawn further subagents. |
0
|
Returns:
| Type | Description |
|---|---|
SubAgentDepsProtocol
|
A new deps instance configured for the subagent. |
Source code in src/subagents_pydantic_ai/protocols.py
MessageBusProtocol¶
subagents_pydantic_ai.MessageBusProtocol
¶
Bases: Protocol
Protocol for message bus implementations.
The message bus enables communication between agents, supporting both fire-and-forget messages and request-response patterns.
Implementations can use different backends: - In-memory (default): Uses asyncio queues - Redis: For distributed multi-process setups - Custom: Any backend implementing this protocol
Example
bus = InMemoryMessageBus()
# Register an agent
queue = bus.register_agent("worker-1")
# Send a message
await bus.send(AgentMessage(
type=MessageType.TASK_UPDATE,
sender="parent",
receiver="worker-1",
payload={"status": "starting"},
))
# Request-response pattern
response = await bus.ask(
sender="parent",
receiver="worker-1",
question="What is your status?",
task_id="task-123",
timeout=30.0,
)
Source code in src/subagents_pydantic_ai/protocols.py
| Python | |
|---|---|
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
send(message)
async
¶
Send a message to a specific agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
AgentMessage
|
The message to send. Must have a valid receiver. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the receiver is not registered. |
Source code in src/subagents_pydantic_ai/protocols.py
ask(sender, receiver, question, task_id, timeout=30.0)
async
¶
Send a question and wait for a response.
This implements a request-response pattern where the sender blocks until the receiver answers or the timeout expires.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sender
|
str
|
ID of the asking agent. |
required |
receiver
|
str
|
ID of the agent to ask. |
required |
question
|
Any
|
The question payload. |
required |
task_id
|
str
|
Task ID for correlation. |
required |
timeout
|
float
|
Maximum time to wait for response in seconds. |
30.0
|
Returns:
| Type | Description |
|---|---|
AgentMessage
|
The response message from the receiver. |
Raises:
| Type | Description |
|---|---|
TimeoutError
|
If no response within timeout. |
KeyError
|
If the receiver is not registered. |
Source code in src/subagents_pydantic_ai/protocols.py
answer(original, answer)
async
¶
Answer a previously received question.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original
|
AgentMessage
|
The original question message. |
required |
answer
|
Any
|
The answer payload. |
required |
register_agent(agent_id)
¶
Register an agent to receive messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_id
|
str
|
Unique identifier for the agent. |
required |
Returns:
| Type | Description |
|---|---|
Queue[AgentMessage]
|
A queue where messages for this agent will be delivered. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If agent_id is already registered. |
Source code in src/subagents_pydantic_ai/protocols.py
| Python | |
|---|---|
unregister_agent(agent_id)
¶
Unregister an agent from the message bus.
After unregistration, messages sent to this agent will raise errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_id
|
str
|
The agent to unregister. |
required |
Source code in src/subagents_pydantic_ai/protocols.py
get_messages(agent_id, timeout=0.0)
async
¶
Get pending messages for an agent.
Non-blocking retrieval of all pending messages in the agent's queue.
Optionally waits up to timeout seconds for at least one message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_id
|
str
|
The agent to get messages for. |
required |
timeout
|
float
|
Maximum time to wait for a message (0 = no wait). |
0.0
|
Returns:
| Type | Description |
|---|---|
list[AgentMessage]
|
List of pending messages (may be empty). |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the agent is not registered. |
Source code in src/subagents_pydantic_ai/protocols.py
InMemoryMessageBus¶
subagents_pydantic_ai.InMemoryMessageBus
dataclass
¶
In-memory message bus using asyncio queues.
This is the default message bus implementation, suitable for single-process applications. For distributed systems, consider implementing a Redis-based bus using the MessageBusProtocol.
Example
bus = InMemoryMessageBus()
# Register agents
parent_queue = bus.register_agent("parent")
worker_queue = bus.register_agent("worker-1")
# Send a message
await bus.send(AgentMessage(
type=MessageType.TASK_ASSIGNED,
sender="parent",
receiver="worker-1",
payload={"task": "analyze data"},
task_id="task-123",
))
# Worker receives message
msg = await worker_queue.get()
Source code in src/subagents_pydantic_ai/message_bus.py
| Python | |
|---|---|
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | |
send(message)
async
¶
Send a message to a specific agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
AgentMessage
|
The message to send. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the receiver is not registered. |
Source code in src/subagents_pydantic_ai/message_bus.py
ask(sender, receiver, question, task_id, timeout=30.0)
async
¶
Send a question and wait for a response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sender
|
str
|
ID of the asking agent. |
required |
receiver
|
str
|
ID of the agent to ask. |
required |
question
|
Any
|
The question payload. |
required |
task_id
|
str
|
Task ID for correlation. |
required |
timeout
|
float
|
Maximum time to wait in seconds. |
30.0
|
Returns:
| Type | Description |
|---|---|
AgentMessage
|
The response message. |
Raises:
| Type | Description |
|---|---|
TimeoutError
|
If no response within timeout. |
KeyError
|
If the receiver is not registered. |
Source code in src/subagents_pydantic_ai/message_bus.py
answer(original, answer)
async
¶
Answer a previously received question.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original
|
AgentMessage
|
The original question message. |
required |
answer
|
Any
|
The answer payload. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the original sender is not registered or if there's no pending question with the correlation_id. |
Source code in src/subagents_pydantic_ai/message_bus.py
register_agent(agent_id)
¶
Register an agent to receive messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_id
|
str
|
Unique identifier for the agent. |
required |
Returns:
| Type | Description |
|---|---|
Queue[AgentMessage]
|
A queue where messages for this agent will be delivered. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If agent_id is already registered. |
Source code in src/subagents_pydantic_ai/message_bus.py
unregister_agent(agent_id)
¶
Unregister an agent from the message bus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_id
|
str
|
The agent to unregister. |
required |
add_handler(handler)
¶
Add a message handler for debugging/logging.
Handlers are called for every message sent through the bus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
Callable[[AgentMessage], Awaitable[None]]
|
Async function that receives messages. |
required |
Source code in src/subagents_pydantic_ai/message_bus.py
| Python | |
|---|---|
remove_handler(handler)
¶
Remove a previously added handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
Callable[[AgentMessage], Awaitable[None]]
|
The handler to remove. |
required |
Source code in src/subagents_pydantic_ai/message_bus.py
is_registered(agent_id)
¶
Check if an agent is registered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_id
|
str
|
The agent ID to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the agent is registered, False otherwise. |
Source code in src/subagents_pydantic_ai/message_bus.py
registered_agents()
¶
Get list of registered agent IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of registered agent IDs. |
get_messages(agent_id, timeout=0.0)
async
¶
Get pending messages for an agent.
Non-blocking retrieval of all pending messages in the agent's queue.
Optionally waits up to timeout seconds for at least one message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_id
|
str
|
The agent to get messages for. |
required |
timeout
|
float
|
Maximum time to wait for a message (0 = no wait). |
0.0
|
Returns:
| Type | Description |
|---|---|
list[AgentMessage]
|
List of pending messages (may be empty). |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the agent is not registered. |
Source code in src/subagents_pydantic_ai/message_bus.py
TaskManager¶
subagents_pydantic_ai.TaskManager
dataclass
¶
Manages background tasks and their lifecycle.
Tracks running tasks, handles cancellation, and provides status querying capabilities.
Attributes:
| Name | Type | Description |
|---|---|---|
tasks |
dict[str, Task[Any]]
|
Dictionary of task_id -> asyncio.Task |
handles |
dict[str, Any]
|
Dictionary of task_id -> TaskHandle |
message_bus |
InMemoryMessageBus
|
Message bus for communication |
Source code in src/subagents_pydantic_ai/message_bus.py
| Python | |
|---|---|
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 | |
create_task(task_id, coro, handle)
¶
Create and track a new background task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
Unique identifier for the task. |
required |
coro
|
Any
|
The coroutine to run. |
required |
handle
|
Any
|
TaskHandle for status tracking. |
required |
Returns:
| Type | Description |
|---|---|
Task[Any]
|
The created asyncio.Task. |
Source code in src/subagents_pydantic_ai/message_bus.py
get_handle(task_id)
¶
Get the handle for a task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task ID. |
required |
Returns:
| Type | Description |
|---|---|
Any | None
|
The TaskHandle if found, None otherwise. |
get_cancel_event(task_id)
¶
Get the cancellation event for a task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task ID. |
required |
Returns:
| Type | Description |
|---|---|
Event | None
|
The cancellation event if found, None otherwise. |
Source code in src/subagents_pydantic_ai/message_bus.py
soft_cancel(task_id)
async
¶
Request cooperative cancellation of a task.
Sets a cancellation event that the task can check periodically. The task is expected to clean up and exit gracefully.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task to cancel. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if cancellation was requested, False if task not found. |
Source code in src/subagents_pydantic_ai/message_bus.py
hard_cancel(task_id)
async
¶
Immediately cancel a task.
Calls cancel() on the asyncio.Task, causing CancelledError to be raised in the task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task to cancel. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if task was cancelled, False if task not found. |
Source code in src/subagents_pydantic_ai/message_bus.py
cleanup_task(task_id)
¶
Clean up resources for a completed task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
The task to clean up. |
required |
list_active_tasks()
¶
Get list of active (non-completed) task IDs.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of task IDs for tasks that haven't completed. |
Source code in src/subagents_pydantic_ai/message_bus.py
create_message_bus¶
subagents_pydantic_ai.create_message_bus(backend='memory', **kwargs)
¶
Create a message bus instance.
Factory function for creating message bus implementations. Currently only supports in-memory backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str
|
The backend type ("memory" is currently supported). |
'memory'
|
**kwargs
|
Any
|
Backend-specific configuration. |
{}
|
Returns:
| Type | Description |
|---|---|
InMemoryMessageBus
|
A message bus instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the backend is not supported. |
Example
Source code in src/subagents_pydantic_ai/message_bus.py
DynamicAgentRegistry¶
subagents_pydantic_ai.DynamicAgentRegistry
dataclass
¶
Registry for dynamically created agents.
Provides storage and management for agents created at runtime. Used by the agent factory toolset to track created agents.
Attributes:
| Name | Type | Description |
|---|---|---|
agents |
dict[str, Any]
|
Dictionary mapping agent names to Agent instances. |
configs |
dict[str, SubAgentConfig]
|
Dictionary mapping agent names to their configurations. |
max_agents |
int | None
|
Maximum number of agents allowed (optional limit). |
Example
Source code in src/subagents_pydantic_ai/registry.py
| Python | |
|---|---|
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | |
register(config, agent)
¶
Register a new agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
SubAgentConfig
|
The agent's configuration. |
required |
agent
|
Any
|
The Agent instance. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If agent name already exists or max_agents reached. |
Source code in src/subagents_pydantic_ai/registry.py
get(name)
¶
Get an agent by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The agent name. |
required |
Returns:
| Type | Description |
|---|---|
Any | None
|
The Agent instance, or None if not found. |
get_config(name)
¶
Get an agent's configuration by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The agent name. |
required |
Returns:
| Type | Description |
|---|---|
SubAgentConfig | None
|
The SubAgentConfig, or None if not found. |
Source code in src/subagents_pydantic_ai/registry.py
get_compiled(name)
¶
Get a compiled agent by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The agent name. |
required |
Returns:
| Type | Description |
|---|---|
CompiledSubAgent | None
|
The CompiledSubAgent, or None if not found. |
Source code in src/subagents_pydantic_ai/registry.py
remove(name)
¶
Remove an agent from the registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The agent name to remove. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if agent was removed, False if not found. |
Source code in src/subagents_pydantic_ai/registry.py
| Python | |
|---|---|
list_agents()
¶
Get list of all registered agent names.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of agent names. |
list_configs()
¶
Get list of all agent configurations.
Returns:
| Type | Description |
|---|---|
list[SubAgentConfig]
|
List of SubAgentConfig for all registered agents. |
list_compiled()
¶
Get list of all compiled agents.
Returns:
| Type | Description |
|---|---|
list[CompiledSubAgent]
|
List of CompiledSubAgent for all registered agents. |
exists(name)
¶
Check if an agent exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The agent name. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if agent exists, False otherwise. |
count()
¶
Get the number of registered agents.
Returns:
| Type | Description |
|---|---|
int
|
Number of agents in the registry. |
clear()
¶
get_summary()
¶
Get a formatted summary of all registered agents.
Returns:
| Type | Description |
|---|---|
str
|
Multi-line string describing all agents. |
Source code in src/subagents_pydantic_ai/registry.py
Usage Examples¶
Implementing SubAgentDepsProtocol¶
from dataclasses import dataclass, field
from typing import Any
@dataclass
class MyDeps:
"""Custom dependencies implementing SubAgentDepsProtocol."""
subagents: dict[str, Any] = field(default_factory=dict)
database_url: str = ""
api_key: str = ""
def clone_for_subagent(self, max_depth: int = 0) -> "MyDeps":
"""Create isolated deps for subagent."""
return MyDeps(
subagents={} if max_depth <= 0 else self.subagents.copy(),
database_url=self.database_url, # Share read-only config
api_key=self.api_key,
)
Implementing Custom Message Bus¶
from subagents_pydantic_ai import MessageBusProtocol, AgentMessage
class RedisMessageBus:
"""Redis-based message bus for distributed systems."""
def __init__(self, redis_url: str):
self.redis = Redis.from_url(redis_url)
async def send(self, message: AgentMessage) -> None:
channel = f"agent:{message.receiver}"
await self.redis.publish(channel, message.json())
async def receive(
self,
agent_id: str,
timeout: float | None = None,
) -> AgentMessage | None:
# Implementation...
pass
async def subscribe(self, agent_id: str) -> None:
pass
async def unsubscribe(self, agent_id: str) -> None:
pass
Using TaskManager¶
from subagents_pydantic_ai import TaskManager, InMemoryMessageBus
bus = InMemoryMessageBus()
manager = TaskManager(message_bus=bus)
# Create a task
handle = await manager.create_task(
subagent_name="researcher",
description="Research Python async",
)
# Check status
status = await manager.get_task_status(handle.task_id)
# Answer a question
await manager.answer_question(handle.task_id, "Use asyncio")
# Cancel a task
await manager.cancel_task(handle.task_id, hard=False)