strands.multiagent.swarm
¶
Swarm Multi-Agent Pattern Implementation.
This module provides a collaborative agent orchestration system where agents work together as a team to solve complex tasks, with shared context and autonomous coordination.
Key Features: - Self-organizing agent teams with shared working memory - Tool-based coordination - Autonomous agent collaboration without central control - Dynamic task distribution based on agent capabilities - Collective intelligence through shared context - Human input via user interrupts raised in BeforeNodeCallEvent hooks and agent nodes
AgentState = JSONSerializableDict
module-attribute
¶
AttributeValue = Union[str, bool, float, int, List[str], List[bool], List[float], List[int], Sequence[str], Sequence[bool], Sequence[int], Sequence[float]]
module-attribute
¶
Messages = List[Message]
module-attribute
¶
A list of messages representing a conversation.
MultiAgentInput = str | list[ContentBlock] | list[InterruptResponseContent]
module-attribute
¶
_DEFAULT_SWARM_ID = 'default_swarm'
module-attribute
¶
logger = logging.getLogger(__name__)
module-attribute
¶
AfterMultiAgentInvocationEvent
dataclass
¶
Bases: BaseHookEvent
Event triggered after orchestrator execution completes.
Attributes:
| Name | Type | Description |
|---|---|---|
source |
MultiAgentBase
|
The multi-agent orchestrator instance |
invocation_state |
dict[str, Any] | None
|
Configuration that user passes in |
Source code in strands/experimental/hooks/multiagent/events.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
should_reverse_callbacks
property
¶
True to invoke callbacks in reverse order.
AfterNodeCallEvent
dataclass
¶
Bases: BaseHookEvent
Event triggered after individual node execution completes.
Attributes:
| Name | Type | Description |
|---|---|---|
source |
MultiAgentBase
|
The multi-agent orchestrator instance |
node_id |
str
|
ID of the node that just completed execution |
invocation_state |
dict[str, Any] | None
|
Configuration that user passes in |
Source code in strands/experimental/hooks/multiagent/events.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | |
should_reverse_callbacks
property
¶
True to invoke callbacks in reverse order.
Agent
¶
Core Agent interface.
An agent orchestrates the following workflow:
- Receives user input
- Processes the input using a language model
- Decides whether to use tools to gather information or perform actions
- Executes those tools and receives results
- Continues reasoning with the new information
- Produces a final response
Source code in strands/agent/agent.py
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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 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 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 | |
system_prompt
property
writable
¶
Get the system prompt as a string for backwards compatibility.
Returns the system prompt as a concatenated string when it contains text content, or None if no text content is present. This maintains backwards compatibility with existing code that expects system_prompt to be a string.
Returns:
| Type | Description |
|---|---|
str | None
|
The system prompt as a string, or None if no text content exists. |
tool
property
¶
Call tool as a function.
Returns:
| Type | Description |
|---|---|
_ToolCaller
|
Tool caller through which user can invoke tool as a function. |
Example
agent = Agent(tools=[calculator])
agent.tool.calculator(...)
tool_names
property
¶
Get a list of all registered tool names.
Returns:
| Type | Description |
|---|---|
list[str]
|
Names of all tools available to this agent. |
__call__(prompt=None, *, invocation_state=None, structured_output_model=None, **kwargs)
¶
Process a natural language prompt through the agent's event loop.
This method implements the conversational interface with multiple input patterns:
- String input: agent("hello!")
- ContentBlock list: agent([{"text": "hello"}, {"image": {...}}])
- Message list: agent([{"role": "user", "content": [{"text": "hello"}]}])
- No input: agent() - uses existing conversation history
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
AgentInput
|
User input in various formats: - str: Simple text input - list[ContentBlock]: Multi-modal content blocks - list[Message]: Complete messages with roles - None: Use existing conversation history |
None
|
invocation_state
|
dict[str, Any] | None
|
Additional parameters to pass through the event loop. |
None
|
structured_output_model
|
Type[BaseModel] | None
|
Pydantic model type(s) for structured output (overrides agent default). |
None
|
**kwargs
|
Any
|
Additional parameters to pass through the event loop.[Deprecating] |
{}
|
Returns:
| Type | Description |
|---|---|
AgentResult
|
Result object containing:
|
Source code in strands/agent/agent.py
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 | |
__del__()
¶
Clean up resources when agent is garbage collected.
Source code in strands/agent/agent.py
514 515 516 517 518 519 | |
__init__(model=None, messages=None, tools=None, system_prompt=None, structured_output_model=None, callback_handler=_DEFAULT_CALLBACK_HANDLER, conversation_manager=None, record_direct_tool_call=True, load_tools_from_directory=False, trace_attributes=None, *, agent_id=None, name=None, description=None, state=None, hooks=None, session_manager=None, tool_executor=None)
¶
Initialize the Agent with the specified configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Union[Model, str, None]
|
Provider for running inference or a string representing the model-id for Bedrock to use. Defaults to strands.models.BedrockModel if None. |
None
|
messages
|
Optional[Messages]
|
List of initial messages to pre-load into the conversation. Defaults to an empty list if None. |
None
|
tools
|
Optional[list[Union[str, dict[str, str], ToolProvider, Any]]]
|
List of tools to make available to the agent. Can be specified as:
If provided, only these tools will be available. If None, all tools will be available. |
None
|
system_prompt
|
Optional[str | list[SystemContentBlock]]
|
System prompt to guide model behavior. Can be a string or a list of SystemContentBlock objects for advanced features like caching. If None, the model will behave according to its default settings. |
None
|
structured_output_model
|
Optional[Type[BaseModel]]
|
Pydantic model type(s) for structured output. When specified, all agent calls will attempt to return structured output of this type. This can be overridden on the agent invocation. Defaults to None (no structured output). |
None
|
callback_handler
|
Optional[Union[Callable[..., Any], _DefaultCallbackHandlerSentinel]]
|
Callback for processing events as they happen during agent execution. If not provided (using the default), a new PrintingCallbackHandler instance is created. If explicitly set to None, null_callback_handler is used. |
_DEFAULT_CALLBACK_HANDLER
|
conversation_manager
|
Optional[ConversationManager]
|
Manager for conversation history and context window. Defaults to strands.agent.conversation_manager.SlidingWindowConversationManager if None. |
None
|
record_direct_tool_call
|
bool
|
Whether to record direct tool calls in message history. Defaults to True. |
True
|
load_tools_from_directory
|
bool
|
Whether to load and automatically reload tools in the |
False
|
trace_attributes
|
Optional[Mapping[str, AttributeValue]]
|
Custom trace attributes to apply to the agent's trace span. |
None
|
agent_id
|
Optional[str]
|
Optional ID for the agent, useful for session management and multi-agent scenarios. Defaults to "default". |
None
|
name
|
Optional[str]
|
name of the Agent Defaults to "Strands Agents". |
None
|
description
|
Optional[str]
|
description of what the Agent does Defaults to None. |
None
|
state
|
Optional[Union[AgentState, dict]]
|
stateful information for the agent. Can be either an AgentState object, or a json serializable dict. Defaults to an empty AgentState object. |
None
|
hooks
|
Optional[list[HookProvider]]
|
hooks to be added to the agent hook registry Defaults to None. |
None
|
session_manager
|
Optional[SessionManager]
|
Manager for handling agent sessions including conversation history and state. If provided, enables session-based persistence and state management. |
None
|
tool_executor
|
Optional[ToolExecutor]
|
Definition of tool execution strategy (e.g., sequential, concurrent, etc.). |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If agent id contains path separators. |
Source code in strands/agent/agent.py
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 | |
cleanup()
¶
Clean up resources used by the agent.
This method cleans up all tool providers that require explicit cleanup, such as MCP clients. It should be called when the agent is no longer needed to ensure proper resource cleanup.
Note: This method uses a "belt and braces" approach with automatic cleanup through finalizers as a fallback, but explicit cleanup is recommended.
Source code in strands/agent/agent.py
502 503 504 505 506 507 508 509 510 511 512 | |
invoke_async(prompt=None, *, invocation_state=None, structured_output_model=None, **kwargs)
async
¶
Process a natural language prompt through the agent's event loop.
This method implements the conversational interface with multiple input patterns: - String input: Simple text input - ContentBlock list: Multi-modal content blocks - Message list: Complete messages with roles - No input: Use existing conversation history
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
AgentInput
|
User input in various formats: - str: Simple text input - list[ContentBlock]: Multi-modal content blocks - list[Message]: Complete messages with roles - None: Use existing conversation history |
None
|
invocation_state
|
dict[str, Any] | None
|
Additional parameters to pass through the event loop. |
None
|
structured_output_model
|
Type[BaseModel] | None
|
Pydantic model type(s) for structured output (overrides agent default). |
None
|
**kwargs
|
Any
|
Additional parameters to pass through the event loop.[Deprecating] |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Result |
AgentResult
|
object containing:
|
Source code in strands/agent/agent.py
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 | |
stream_async(prompt=None, *, invocation_state=None, structured_output_model=None, **kwargs)
async
¶
Process a natural language prompt and yield events as an async iterator.
This method provides an asynchronous interface for streaming agent events with multiple input patterns: - String input: Simple text input - ContentBlock list: Multi-modal content blocks - Message list: Complete messages with roles - No input: Use existing conversation history
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
AgentInput
|
User input in various formats: - str: Simple text input - list[ContentBlock]: Multi-modal content blocks - list[Message]: Complete messages with roles - None: Use existing conversation history |
None
|
invocation_state
|
dict[str, Any] | None
|
Additional parameters to pass through the event loop. |
None
|
structured_output_model
|
Type[BaseModel] | None
|
Pydantic model type(s) for structured output (overrides agent default). |
None
|
**kwargs
|
Any
|
Additional parameters to pass to the event loop.[Deprecating] |
{}
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[Any]
|
An async iterator that yields events. Each event is a dictionary containing information about the current state of processing, such as:
|
Raises:
| Type | Description |
|---|---|
Exception
|
Any exceptions from the agent invocation will be propagated to the caller. |
Example
async for event in agent.stream_async("Analyze this data"):
if "data" in event:
yield event["data"]
Source code in strands/agent/agent.py
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 | |
structured_output(output_model, prompt=None)
¶
This method allows you to get structured output from the agent.
If you pass in a prompt, it will be used temporarily without adding it to the conversation history. If you don't pass in a prompt, it will use only the existing conversation history to respond.
For smaller models, you may want to use the optional prompt to add additional instructions to explicitly instruct the model to output the structured data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_model
|
Type[T]
|
The output model (a JSON schema written as a Pydantic BaseModel) that the agent will use when responding. |
required |
prompt
|
AgentInput
|
The prompt to use for the agent in various formats: - str: Simple text input - list[ContentBlock]: Multi-modal content blocks - list[Message]: Complete messages with roles - None: Use existing conversation history |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If no conversation history or prompt is provided. |
Source code in strands/agent/agent.py
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 | |
structured_output_async(output_model, prompt=None)
async
¶
This method allows you to get structured output from the agent.
If you pass in a prompt, it will be used temporarily without adding it to the conversation history. If you don't pass in a prompt, it will use only the existing conversation history to respond.
For smaller models, you may want to use the optional prompt to add additional instructions to explicitly instruct the model to output the structured data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_model
|
Type[T]
|
The output model (a JSON schema written as a Pydantic BaseModel) that the agent will use when responding. |
required |
prompt
|
AgentInput
|
The prompt to use for the agent (will not be added to conversation history). |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If no conversation history or prompt is provided. |
-
Source code in strands/agent/agent.py
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 | |
BeforeMultiAgentInvocationEvent
dataclass
¶
Bases: BaseHookEvent
Event triggered before orchestrator execution starts.
Attributes:
| Name | Type | Description |
|---|---|---|
source |
MultiAgentBase
|
The multi-agent orchestrator instance |
invocation_state |
dict[str, Any] | None
|
Configuration that user passes in |
Source code in strands/experimental/hooks/multiagent/events.py
90 91 92 93 94 95 96 97 98 99 100 | |
BeforeNodeCallEvent
dataclass
¶
Bases: BaseHookEvent, _Interruptible
Event triggered before individual node execution starts.
Attributes:
| Name | Type | Description |
|---|---|---|
source |
MultiAgentBase
|
The multi-agent orchestrator instance |
node_id |
str
|
ID of the node about to execute |
invocation_state |
dict[str, Any] | None
|
Configuration that user passes in |
cancel_node |
bool | str
|
A user defined message that when set, will cancel the node execution with status FAILED.
The message will be emitted under a MultiAgentNodeCancel event. If set to |
Source code in strands/experimental/hooks/multiagent/events.py
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 | |
ContentBlock
¶
Bases: TypedDict
A block of content for a message that you pass to, or receive from, a model.
Attributes:
| Name | Type | Description |
|---|---|---|
cachePoint |
CachePoint
|
A cache point configuration to optimize conversation history. |
document |
DocumentContent
|
A document to include in the message. |
guardContent |
GuardContent
|
Contains the content to assess with the guardrail. |
image |
ImageContent
|
Image to include in the message. |
reasoningContent |
ReasoningContentBlock
|
Contains content regarding the reasoning that is carried out by the model. |
text |
str
|
Text to include in the message. |
toolResult |
ToolResult
|
The result for a tool request that a model makes. |
toolUse |
ToolUse
|
Information about a tool use request from a model. |
video |
VideoContent
|
Video to include in the message. |
citationsContent |
CitationsContentBlock
|
Contains the citations for a document. |
Source code in strands/types/content.py
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 | |
HookProvider
¶
Bases: Protocol
Protocol for objects that provide hook callbacks to an agent.
Hook providers offer a composable way to extend agent functionality by subscribing to various events in the agent lifecycle. This protocol enables building reusable components that can hook into agent events.
Example
class MyHookProvider(HookProvider):
def register_hooks(self, registry: HookRegistry) -> None:
registry.add_callback(StartRequestEvent, self.on_request_start)
registry.add_callback(EndRequestEvent, self.on_request_end)
agent = Agent(hooks=[MyHookProvider()])
Source code in strands/hooks/registry.py
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 | |
register_hooks(registry, **kwargs)
¶
Register callback functions for specific event types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
HookRegistry
|
The hook registry to register callbacks with. |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Source code in strands/hooks/registry.py
106 107 108 109 110 111 112 113 | |
HookRegistry
¶
Registry for managing hook callbacks associated with event types.
The HookRegistry maintains a mapping of event types to callback functions and provides methods for registering callbacks and invoking them when events occur.
The registry handles callback ordering, including reverse ordering for cleanup events, and provides type-safe event dispatching.
Source code in strands/hooks/registry.py
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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 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 | |
__init__()
¶
Initialize an empty hook registry.
Source code in strands/hooks/registry.py
155 156 157 | |
add_callback(event_type, callback)
¶
Register a callback function for a specific event type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_type
|
Type[TEvent]
|
The class type of events this callback should handle. |
required |
callback
|
HookCallback[TEvent]
|
The callback function to invoke when events of this type occur. |
required |
Example
def my_handler(event: StartRequestEvent):
print("Request started")
registry.add_callback(StartRequestEvent, my_handler)
Source code in strands/hooks/registry.py
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | |
add_hook(hook)
¶
Register all callbacks from a hook provider.
This method allows bulk registration of callbacks by delegating to the hook provider's register_hooks method. This is the preferred way to register multiple related callbacks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hook
|
HookProvider
|
The hook provider containing callbacks to register. |
required |
Example
class MyHooks(HookProvider):
def register_hooks(self, registry: HookRegistry):
registry.add_callback(StartRequestEvent, self.on_start)
registry.add_callback(EndRequestEvent, self.on_end)
registry.add_hook(MyHooks())
Source code in strands/hooks/registry.py
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
get_callbacks_for(event)
¶
Get callbacks registered for the given event in the appropriate order.
This method returns callbacks in registration order for normal events, or reverse registration order for events that have should_reverse_callbacks=True. This enables proper cleanup ordering for teardown events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
TEvent
|
The event to get callbacks for. |
required |
Yields:
| Type | Description |
|---|---|
HookCallback[TEvent]
|
Callback functions registered for this event type, in the appropriate order. |
Example
event = EndRequestEvent(agent=my_agent)
for callback in registry.get_callbacks_for(event):
callback(event)
Source code in strands/hooks/registry.py
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 | |
has_callbacks()
¶
Check if the registry has any registered callbacks.
Returns:
| Type | Description |
|---|---|
bool
|
True if there are any registered callbacks, False otherwise. |
Example
if registry.has_callbacks():
print("Registry has callbacks registered")
Source code in strands/hooks/registry.py
296 297 298 299 300 301 302 303 304 305 306 307 308 | |
invoke_callbacks(event)
¶
Invoke all registered callbacks for the given event.
This method finds all callbacks registered for the event's type and invokes them in the appropriate order. For events with should_reverse_callbacks=True, callbacks are invoked in reverse registration order. Any exceptions raised by callback functions will propagate to the caller.
Additionally, this method aggregates interrupts raised by the user to instantiate human-in-the-loop workflows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
TInvokeEvent
|
The event to dispatch to registered callbacks. |
required |
Returns:
| Type | Description |
|---|---|
tuple[TInvokeEvent, list[Interrupt]]
|
The event dispatched to registered callbacks and any interrupts raised by the user. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If at least one callback is async. |
ValueError
|
If interrupt name is used more than once. |
Example
event = StartRequestEvent(agent=my_agent)
registry.invoke_callbacks(event)
Source code in strands/hooks/registry.py
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | |
invoke_callbacks_async(event)
async
¶
Invoke all registered callbacks for the given event.
This method finds all callbacks registered for the event's type and invokes them in the appropriate order. For events with should_reverse_callbacks=True, callbacks are invoked in reverse registration order. Any exceptions raised by callback functions will propagate to the caller.
Additionally, this method aggregates interrupts raised by the user to instantiate human-in-the-loop workflows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
TInvokeEvent
|
The event to dispatch to registered callbacks. |
required |
Returns:
| Type | Description |
|---|---|
tuple[TInvokeEvent, list[Interrupt]]
|
The event dispatched to registered callbacks and any interrupts raised by the user. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If interrupt name is used more than once. |
Example
event = StartRequestEvent(agent=my_agent)
await registry.invoke_callbacks_async(event)
Source code in strands/hooks/registry.py
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 | |
Interrupt
dataclass
¶
Represents an interrupt that can pause agent execution for human-in-the-loop workflows.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier. |
name |
str
|
User defined name. |
reason |
Any
|
User provided reason for raising the interrupt. |
response |
Any
|
Human response provided when resuming the agent after an interrupt. |
Source code in strands/interrupt.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
to_dict()
¶
Serialize to dict for session management.
Source code in strands/interrupt.py
27 28 29 | |
Metrics
¶
Bases: TypedDict
Performance metrics for model interactions.
Attributes:
| Name | Type | Description |
|---|---|---|
latencyMs |
int
|
Latency of the model request in milliseconds. |
timeToFirstByteMs |
int
|
Latency from sending model request to first content chunk (contentBlockDelta or contentBlockStart) from the model in milliseconds. |
Source code in strands/types/event_loop.py
26 27 28 29 30 31 32 33 34 35 36 | |
MultiAgentBase
¶
Bases: ABC
Base class for multi-agent helpers.
This class integrates with existing Strands Agent instances and provides multi-agent orchestration capabilities.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique MultiAgent id for session management,etc. |
Source code in strands/multiagent/base.py
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 | |
__call__(task, invocation_state=None, **kwargs)
¶
Invoke synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
MultiAgentInput
|
The task to execute |
required |
invocation_state
|
dict[str, Any] | None
|
Additional state/context passed to underlying agents. Defaults to None to avoid mutable default argument issues. |
None
|
**kwargs
|
Any
|
Additional keyword arguments passed to underlying agents. |
{}
|
Source code in strands/multiagent/base.py
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | |
deserialize_state(payload)
¶
Restore orchestrator state from a session dict.
Source code in strands/multiagent/base.py
252 253 254 | |
invoke_async(task, invocation_state=None, **kwargs)
abstractmethod
async
¶
Invoke asynchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
MultiAgentInput
|
The task to execute |
required |
invocation_state
|
dict[str, Any] | None
|
Additional state/context passed to underlying agents. Defaults to None to avoid mutable default argument issues. |
None
|
**kwargs
|
Any
|
Additional keyword arguments passed to underlying agents. |
{}
|
Source code in strands/multiagent/base.py
189 190 191 192 193 194 195 196 197 198 199 200 201 | |
serialize_state()
¶
Return a JSON-serializable snapshot of the orchestrator state.
Source code in strands/multiagent/base.py
248 249 250 | |
stream_async(task, invocation_state=None, **kwargs)
async
¶
Stream events during multi-agent execution.
Default implementation executes invoke_async and yields the result as a single event. Subclasses can override this method to provide true streaming capabilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
MultiAgentInput
|
The task to execute |
required |
invocation_state
|
dict[str, Any] | None
|
Additional state/context passed to underlying agents. Defaults to None to avoid mutable default argument issues. |
None
|
**kwargs
|
Any
|
Additional keyword arguments passed to underlying agents. |
{}
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[dict[str, Any]]
|
Dictionary events containing multi-agent execution information including: |
AsyncIterator[dict[str, Any]]
|
|
AsyncIterator[dict[str, Any]]
|
|
AsyncIterator[dict[str, Any]]
|
|
Source code in strands/multiagent/base.py
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | |
MultiAgentHandoffEvent
¶
Bases: TypedEvent
Event emitted during node transitions in multi-agent systems.
Supports both single handoffs (Swarm) and batch transitions (Graph). For Swarm: Single node-to-node handoffs with a message. For Graph: Batch transitions where multiple nodes complete and multiple nodes begin.
Source code in strands/types/_events.py
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 | |
__init__(from_node_ids, to_node_ids, message=None)
¶
Initialize with handoff information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
from_node_ids
|
list[str]
|
List of node ID(s) completing execution. - Swarm: Single-element list ["agent_a"] - Graph: Multi-element list ["node1", "node2"] |
required |
to_node_ids
|
list[str]
|
List of node ID(s) beginning execution. - Swarm: Single-element list ["agent_b"] - Graph: Multi-element list ["node3", "node4"] |
required |
message
|
str | None
|
Optional message explaining the transition (typically used in Swarm) |
None
|
Examples:
Swarm handoff: MultiAgentHandoffEvent(["researcher"], ["analyst"], "Need calculations") Graph batch: MultiAgentHandoffEvent(["node1", "node2"], ["node3", "node4"])
Source code in strands/types/_events.py
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 | |
MultiAgentInitializedEvent
dataclass
¶
Bases: BaseHookEvent
Event triggered when multi-agent orchestrator initialized.
Attributes:
| Name | Type | Description |
|---|---|---|
source |
MultiAgentBase
|
The multi-agent orchestrator instance |
invocation_state |
dict[str, Any] | None
|
Configuration that user passes in |
Source code in strands/experimental/hooks/multiagent/events.py
21 22 23 24 25 26 27 28 29 30 31 | |
MultiAgentNodeCancelEvent
¶
Bases: TypedEvent
Event emitted when a user cancels node execution from their BeforeNodeCallEvent hook.
Source code in strands/types/_events.py
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 | |
__init__(node_id, message)
¶
Initialize with cancel message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_id
|
str
|
Unique identifier for the node. |
required |
message
|
str
|
The node cancellation message. |
required |
Source code in strands/types/_events.py
532 533 534 535 536 537 538 539 540 541 542 543 544 545 | |
MultiAgentNodeInterruptEvent
¶
Bases: TypedEvent
Event emitted when a node is interrupted.
Source code in strands/types/_events.py
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 | |
interrupts
property
¶
The interrupt instances.
__init__(node_id, interrupts)
¶
Set interrupt in the event payload.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_id
|
str
|
Unique identifier for the node generating the event. |
required |
interrupts
|
list[Interrupt]
|
Interrupts raised by user. |
required |
Source code in strands/types/_events.py
551 552 553 554 555 556 557 558 559 560 561 562 563 564 | |
MultiAgentNodeStartEvent
¶
Bases: TypedEvent
Event emitted when a node begins execution in multi-agent context.
Source code in strands/types/_events.py
428 429 430 431 432 433 434 435 436 437 438 | |
__init__(node_id, node_type)
¶
Initialize with node information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_id
|
str
|
Unique identifier for the node |
required |
node_type
|
str
|
Type of node ("agent", "swarm", "graph") |
required |
Source code in strands/types/_events.py
431 432 433 434 435 436 437 438 | |
MultiAgentNodeStopEvent
¶
Bases: TypedEvent
Event emitted when a node stops execution.
Similar to EventLoopStopEvent but for individual nodes in multi-agent orchestration. Provides the complete NodeResult which contains execution details, metrics, and status.
Source code in strands/types/_events.py
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 | |
__init__(node_id, node_result)
¶
Initialize with stop information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_id
|
str
|
Unique identifier for the node |
required |
node_result
|
NodeResult
|
Complete result from the node execution containing result, execution_time, status, accumulated_usage, accumulated_metrics, and execution_count |
required |
Source code in strands/types/_events.py
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 | |
MultiAgentNodeStreamEvent
¶
Bases: TypedEvent
Event emitted during node execution - forwards agent events with node context.
Source code in strands/types/_events.py
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 | |
__init__(node_id, agent_event)
¶
Initialize with node context and agent event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_id
|
str
|
Unique identifier for the node generating the event |
required |
agent_event
|
dict[str, Any]
|
The original agent event data |
required |
Source code in strands/types/_events.py
513 514 515 516 517 518 519 520 521 522 523 524 525 526 | |
MultiAgentResult
dataclass
¶
Result from multi-agent execution with accumulated metrics.
Source code in strands/multiagent/base.py
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 | |
from_dict(data)
classmethod
¶
Rehydrate a MultiAgentResult from persisted JSON.
Source code in strands/multiagent/base.py
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
to_dict()
¶
Convert MultiAgentResult to JSON-serializable dict.
Source code in strands/multiagent/base.py
163 164 165 166 167 168 169 170 171 172 173 174 | |
MultiAgentResultEvent
¶
Bases: TypedEvent
Event emitted when multi-agent execution completes with final result.
Source code in strands/types/_events.py
416 417 418 419 420 421 422 423 424 425 | |
__init__(result)
¶
Initialize with multi-agent result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
MultiAgentResult
|
The final result from multi-agent execution (SwarmResult, GraphResult, etc.) |
required |
Source code in strands/types/_events.py
419 420 421 422 423 424 425 | |
NodeResult
dataclass
¶
Unified result from node execution - handles both Agent and nested MultiAgentBase results.
Source code in strands/multiagent/base.py
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 | |
from_dict(data)
classmethod
¶
Rehydrate a NodeResult from persisted JSON.
Source code in strands/multiagent/base.py
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 | |
get_agent_results()
¶
Get all AgentResult objects from this node, flattened if nested.
Source code in strands/multiagent/base.py
58 59 60 61 62 63 64 65 66 67 68 69 | |
to_dict()
¶
Convert NodeResult to JSON-serializable dict, ignoring state field.
Source code in strands/multiagent/base.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
SessionManager
¶
Bases: HookProvider, ABC
Abstract interface for managing sessions.
A session manager is in charge of persisting the conversation and state of an agent across its interaction. Changes made to the agents conversation, state, or other attributes should be persisted immediately after they are changed. The different methods introduced in this class are called at important lifecycle events for an agent, and should be persisted in the session.
Source code in strands/session/session_manager.py
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 | |
append_bidi_message(message, agent, **kwargs)
¶
Append a message to the bidirectional agent's session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Message
|
Message to add to the agent in the session |
required |
agent
|
BidiAgent
|
BidiAgent to append the message to |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Source code in strands/session/session_manager.py
143 144 145 146 147 148 149 150 151 152 153 154 155 | |
append_message(message, agent, **kwargs)
abstractmethod
¶
Append a message to the agent's session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Message
|
Message to add to the agent in the session |
required |
agent
|
Agent
|
Agent to append the message to |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Source code in strands/session/session_manager.py
72 73 74 75 76 77 78 79 80 | |
initialize(agent, **kwargs)
abstractmethod
¶
Initialize an agent with a session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent
|
Agent
|
Agent to initialize |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Source code in strands/session/session_manager.py
91 92 93 94 95 96 97 98 | |
initialize_bidi_agent(agent, **kwargs)
¶
Initialize a bidirectional agent with a session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent
|
BidiAgent
|
BidiAgent to initialize |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Source code in strands/session/session_manager.py
130 131 132 133 134 135 136 137 138 139 140 141 | |
initialize_multi_agent(source, **kwargs)
¶
Read multi-agent state from persistent storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
source
|
MultiAgentBase
|
Multi-agent state to initialize. |
required |
Returns:
| Type | Description |
|---|---|
None
|
Multi-agent state dictionary or empty dict if not found. |
Source code in strands/session/session_manager.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
redact_latest_message(redact_message, agent, **kwargs)
abstractmethod
¶
Redact the message most recently appended to the agent in the session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redact_message
|
Message
|
New message to use that contains the redact content |
required |
agent
|
Agent
|
Agent to apply the message redaction to |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Source code in strands/session/session_manager.py
62 63 64 65 66 67 68 69 70 | |
register_hooks(registry, **kwargs)
¶
Register hooks for persisting the agent to the session.
Source code in strands/session/session_manager.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | |
sync_agent(agent, **kwargs)
abstractmethod
¶
Serialize and sync the agent with the session storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent
|
Agent
|
Agent who should be synchronized with the session storage |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Source code in strands/session/session_manager.py
82 83 84 85 86 87 88 89 | |
sync_bidi_agent(agent, **kwargs)
¶
Serialize and sync the bidirectional agent with the session storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent
|
BidiAgent
|
BidiAgent who should be synchronized with the session storage |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Source code in strands/session/session_manager.py
157 158 159 160 161 162 163 164 165 166 167 168 | |
sync_multi_agent(source, **kwargs)
¶
Serialize and sync multi-agent with the session storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
MultiAgentBase
|
Multi-agent source object to persist |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Source code in strands/session/session_manager.py
100 101 102 103 104 105 106 107 108 109 110 111 | |
SharedContext
dataclass
¶
Shared context between swarm nodes.
Source code in strands/multiagent/swarm.py
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 | |
add_context(node, key, value)
¶
Add context.
Source code in strands/multiagent/swarm.py
117 118 119 120 121 122 123 124 | |
Status
¶
Bases: Enum
Execution status for both graphs and nodes.
Attributes:
| Name | Type | Description |
|---|---|---|
PENDING |
Task has not started execution yet. |
|
EXECUTING |
Task is currently running. |
|
COMPLETED |
Task finished successfully. |
|
FAILED |
Task encountered an error and could not complete. |
|
INTERRUPTED |
Task was interrupted by user. |
Source code in strands/multiagent/base.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | |
Swarm
¶
Bases: MultiAgentBase
Self-organizing collaborative agent teams with shared working memory.
Source code in strands/multiagent/swarm.py
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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 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 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 | |
__call__(task, invocation_state=None, **kwargs)
¶
Invoke the swarm synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
MultiAgentInput
|
The task to execute |
required |
invocation_state
|
dict[str, Any] | None
|
Additional state/context passed to underlying agents. Defaults to None to avoid mutable default argument issues. |
None
|
**kwargs
|
Any
|
Keyword arguments allowing backward compatible future changes. |
{}
|
Source code in strands/multiagent/swarm.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
__init__(nodes, *, entry_point=None, max_handoffs=20, max_iterations=20, execution_timeout=900.0, node_timeout=300.0, repetitive_handoff_detection_window=0, repetitive_handoff_min_unique_agents=0, session_manager=None, hooks=None, id=_DEFAULT_SWARM_ID, trace_attributes=None)
¶
Initialize Swarm with agents and configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
Unique swarm id (default: "default_swarm") |
_DEFAULT_SWARM_ID
|
nodes
|
list[Agent]
|
List of nodes (e.g. Agent) to include in the swarm |
required |
entry_point
|
Agent | None
|
Agent to start with. If None, uses the first agent (default: None) |
None
|
max_handoffs
|
int
|
Maximum handoffs to agents and users (default: 20) |
20
|
max_iterations
|
int
|
Maximum node executions within the swarm (default: 20) |
20
|
execution_timeout
|
float
|
Total execution timeout in seconds (default: 900.0) |
900.0
|
node_timeout
|
float
|
Individual node timeout in seconds (default: 300.0) |
300.0
|
repetitive_handoff_detection_window
|
int
|
Number of recent nodes to check for repetitive handoffs Disabled by default (default: 0) |
0
|
repetitive_handoff_min_unique_agents
|
int
|
Minimum unique agents required in recent sequence Disabled by default (default: 0) |
0
|
session_manager
|
Optional[SessionManager]
|
Session manager for persisting graph state and execution history (default: None) |
None
|
hooks
|
Optional[list[HookProvider]]
|
List of hook providers for monitoring and extending graph execution behavior (default: None) |
None
|
trace_attributes
|
Optional[Mapping[str, AttributeValue]]
|
Custom trace attributes to apply to the agent's trace span (default: None) |
None
|
Source code in strands/multiagent/swarm.py
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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | |
deserialize_state(payload)
¶
Restore swarm state from a session dict and prepare for execution.
This method handles two scenarios: 1. If the persisted status is COMPLETED, FAILED resets all nodes and graph state to allow re-execution from the beginning. 2. Otherwise, restores the persisted state and prepares to resume execution from the next ready nodes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
dict[str, Any]
|
Dictionary containing persisted state data including status, completed nodes, results, and next nodes to execute. |
required |
Source code in strands/multiagent/swarm.py
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 | |
invoke_async(task, invocation_state=None, **kwargs)
async
¶
Invoke the swarm asynchronously.
This method uses stream_async internally and consumes all events until completion, following the same pattern as the Agent class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
MultiAgentInput
|
The task to execute |
required |
invocation_state
|
dict[str, Any] | None
|
Additional state/context passed to underlying agents. Defaults to None to avoid mutable default argument issues. |
None
|
**kwargs
|
Any
|
Keyword arguments allowing backward compatible future changes. |
{}
|
Source code in strands/multiagent/swarm.py
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 | |
serialize_state()
¶
Serialize the current swarm state to a dictionary.
Source code in strands/multiagent/swarm.py
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 | |
stream_async(task, invocation_state=None, **kwargs)
async
¶
Stream events during swarm execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
MultiAgentInput
|
The task to execute |
required |
invocation_state
|
dict[str, Any] | None
|
Additional state/context passed to underlying agents. Defaults to None to avoid mutable default argument issues. |
None
|
**kwargs
|
Any
|
Keyword arguments allowing backward compatible future changes. |
{}
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[dict[str, Any]]
|
Dictionary events during swarm execution, such as: |
AsyncIterator[dict[str, Any]]
|
|
AsyncIterator[dict[str, Any]]
|
|
AsyncIterator[dict[str, Any]]
|
|
AsyncIterator[dict[str, Any]]
|
|
AsyncIterator[dict[str, Any]]
|
|
Source code in strands/multiagent/swarm.py
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 | |
SwarmNode
dataclass
¶
Represents a node (e.g. Agent) in the swarm.
Source code in strands/multiagent/swarm.py
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 | |
__eq__(other)
¶
Return equality for SwarmNode based on node_id.
Source code in strands/multiagent/swarm.py
81 82 83 84 85 | |
__hash__()
¶
Return hash for SwarmNode based on node_id.
Source code in strands/multiagent/swarm.py
77 78 79 | |
__post_init__()
¶
Capture initial executor state after initialization.
Source code in strands/multiagent/swarm.py
71 72 73 74 75 | |
__repr__()
¶
Return detailed representation of SwarmNode.
Source code in strands/multiagent/swarm.py
91 92 93 | |
__str__()
¶
Return string representation of SwarmNode.
Source code in strands/multiagent/swarm.py
87 88 89 | |
reset_executor_state()
¶
Reset SwarmNode executor state to initial state when swarm was created.
If Swarm is resuming from an interrupt, we reset the executor state from the interrupt context.
Source code in strands/multiagent/swarm.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 | |
SwarmResult
dataclass
¶
Bases: MultiAgentResult
Result from swarm execution - extends MultiAgentResult with swarm-specific details.
Source code in strands/multiagent/swarm.py
221 222 223 224 225 | |
SwarmState
dataclass
¶
Current state of swarm execution.
Source code in strands/multiagent/swarm.py
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 | |
should_continue(*, max_handoffs, max_iterations, execution_timeout, repetitive_handoff_detection_window, repetitive_handoff_min_unique_agents)
¶
Check if the swarm should continue.
Returns: (should_continue, reason)
Source code in strands/multiagent/swarm.py
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 | |
Usage
¶
Bases: TypedDict
Token usage information for model interactions.
Attributes:
| Name | Type | Description |
|---|---|---|
inputTokens |
Required[int]
|
Number of tokens sent in the request to the model. |
outputTokens |
Required[int]
|
Number of tokens that the model generated for the request. |
totalTokens |
Required[int]
|
Total number of tokens (input + output). |
cacheReadInputTokens |
int
|
Number of tokens read from cache (optional). |
cacheWriteInputTokens |
int
|
Number of tokens written to cache (optional). |
Source code in strands/types/event_loop.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
_InterruptState
dataclass
¶
Track the state of interrupt events raised by the user.
Note, interrupt state is cleared after resuming.
Attributes:
| Name | Type | Description |
|---|---|---|
interrupts |
dict[str, Interrupt]
|
Interrupts raised by the user. |
context |
dict[str, Any]
|
Additional context associated with an interrupt event. |
activated |
bool
|
True if agent is in an interrupt state, False otherwise. |
Source code in strands/interrupt.py
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 | |
activate()
¶
Activate the interrupt state.
Source code in strands/interrupt.py
56 57 58 | |
deactivate()
¶
Deacitvate the interrupt state.
Interrupts and context are cleared.
Source code in strands/interrupt.py
60 61 62 63 64 65 66 67 | |
from_dict(data)
classmethod
¶
Initiailize interrupt state from serialized interrupt state.
Interrupt state can be serialized with the to_dict method.
Source code in strands/interrupt.py
108 109 110 111 112 113 114 115 116 117 118 119 120 | |
resume(prompt)
¶
Configure the interrupt state if resuming from an interrupt event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
AgentInput
|
User responses if resuming from interrupt. |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If in interrupt state but user did not provide responses. |
Source code in strands/interrupt.py
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 | |
to_dict()
¶
Serialize to dict for session management.
Source code in strands/interrupt.py
104 105 106 | |
get_tracer()
¶
Get or create the global tracer.
Returns:
| Type | Description |
|---|---|
Tracer
|
The global tracer instance. |
Source code in strands/telemetry/tracer.py
872 873 874 875 876 877 878 879 880 881 882 883 | |
run_async(async_func)
¶
Run an async function in a separate thread to avoid event loop conflicts.
This utility handles the common pattern of running async code from sync contexts by using ThreadPoolExecutor to isolate the async execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
async_func
|
Callable[[], Awaitable[T]]
|
A callable that returns an awaitable |
required |
Returns:
| Type | Description |
|---|---|
T
|
The result of the async function |
Source code in strands/_async.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
tool(func=None, description=None, inputSchema=None, name=None, context=False)
¶
tool(__func: Callable[P, R]) -> DecoratedFunctionTool[P, R]
tool(
description: Optional[str] = None,
inputSchema: Optional[JSONSchema] = None,
name: Optional[str] = None,
context: bool | str = False,
) -> Callable[
[Callable[P, R]], DecoratedFunctionTool[P, R]
]
Decorator that transforms a Python function into a Strands tool.
This decorator seamlessly enables a function to be called both as a regular Python function and as a Strands tool. It extracts metadata from the function's signature, docstring, and type hints to generate an OpenAPI-compatible tool specification.
When decorated, a function:
- Still works as a normal function when called directly with arguments
- Processes tool use API calls when provided with a tool use dictionary
- Validates inputs against the function's type hints and parameter spec
- Formats return values according to the expected Strands tool result format
- Provides automatic error handling and reporting
The decorator can be used in two ways:
- As a simple decorator: @tool
- With parameters: @tool(name="custom_name", description="Custom description")
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Optional[Callable[P, R]]
|
The function to decorate. When used as a simple decorator, this is the function being decorated. When used with parameters, this will be None. |
None
|
description
|
Optional[str]
|
Optional custom description to override the function's docstring. |
None
|
inputSchema
|
Optional[JSONSchema]
|
Optional custom JSON schema to override the automatically generated schema. |
None
|
name
|
Optional[str]
|
Optional custom name to override the function's name. |
None
|
context
|
bool | str
|
When provided, places an object in the designated parameter. If True, the param name defaults to 'tool_context', or if an override is needed, set context equal to a string to designate the param name. |
False
|
Returns:
| Type | Description |
|---|---|
Union[DecoratedFunctionTool[P, R], Callable[[Callable[P, R]], DecoratedFunctionTool[P, R]]]
|
An AgentTool that also mimics the original function when invoked |
Example
@tool
def my_tool(name: str, count: int = 1) -> str:
# Does something useful with the provided parameters.
#
# Parameters:
# name: The name to process
# count: Number of times to process (default: 1)
#
# Returns:
# A message with the result
return f"Processed {name} {count} times"
agent = Agent(tools=[my_tool])
agent.my_tool(name="example", count=3)
# Returns: {
# "toolUseId": "123",
# "status": "success",
# "content": [{"text": "Processed example 3 times"}]
# }
Example with parameters
@tool(name="custom_tool", description="A tool with a custom name and description", context=True)
def my_tool(name: str, count: int = 1, tool_context: ToolContext) -> str:
tool_id = tool_context["tool_use"]["toolUseId"]
return f"Processed {name} {count} times with tool ID {tool_id}"
Source code in strands/tools/decorator.py
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 | |