strands.multiagent.graph
¶
Directed Graph Multi-Agent Pattern Implementation.
This module provides a deterministic graph-based agent orchestration system where agents or MultiAgentBase instances (like Swarm or Graph) are nodes in a graph, executed according to edge dependencies, with output from one node passed as input to connected nodes.
Key Features: - Agents and MultiAgentBase instances (Swarm, Graph, etc.) as graph nodes - Deterministic execution based on dependency resolution - Output propagation along edges - Support for cyclic graphs (feedback loops) - Clear dependency management - Supports nested graphs (Graph as a node in another Graph)
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_GRAPH_ID = 'default_graph'
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 | |
Graph
¶
Bases: MultiAgentBase
Directed Graph multi-agent orchestration with configurable revisit behavior.
Source code in strands/multiagent/graph.py
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 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 | |
__call__(task, invocation_state=None, **kwargs)
¶
Invoke the graph 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/graph.py
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 | |
__init__(nodes, edges, entry_points, max_node_executions=None, execution_timeout=None, node_timeout=None, reset_on_revisit=False, session_manager=None, hooks=None, id=_DEFAULT_GRAPH_ID, trace_attributes=None)
¶
Initialize Graph with execution limits and reset behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
dict[str, GraphNode]
|
Dictionary of node_id to GraphNode |
required |
edges
|
set[GraphEdge]
|
Set of GraphEdge objects |
required |
entry_points
|
set[GraphNode]
|
Set of GraphNode objects that are entry points |
required |
max_node_executions
|
Optional[int]
|
Maximum total node executions (default: None - no limit) |
None
|
execution_timeout
|
Optional[float]
|
Total execution timeout in seconds (default: None - no limit) |
None
|
node_timeout
|
Optional[float]
|
Individual node timeout in seconds (default: None - no limit) |
None
|
reset_on_revisit
|
bool
|
Whether to reset node state when revisited (default: False) |
False
|
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
|
id
|
str
|
Unique graph id (default: None) |
_DEFAULT_GRAPH_ID
|
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/graph.py
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 | |
deserialize_state(payload)
¶
Restore graph state from a session dict and prepare for execution.
This method handles two scenarios: 1. If the graph execution ended (no next_nodes_to_execute, eg: Completed, or Failed with dead end nodes), resets all nodes and graph state to allow re-execution from the beginning. 2. If the graph execution was interrupted mid-execution (has next_nodes_to_execute), 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/graph.py
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 | |
invoke_async(task, invocation_state=None, **kwargs)
async
¶
Invoke the graph 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/graph.py
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 | |
serialize_state()
¶
Serialize the current graph state to a dictionary.
Source code in strands/multiagent/graph.py
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 | |
stream_async(task, invocation_state=None, **kwargs)
async
¶
Stream events during graph 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 graph execution, such as: |
AsyncIterator[dict[str, Any]]
|
|
AsyncIterator[dict[str, Any]]
|
|
AsyncIterator[dict[str, Any]]
|
|
AsyncIterator[dict[str, Any]]
|
|
Source code in strands/multiagent/graph.py
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 | |
GraphBuilder
¶
Builder pattern for constructing graphs.
Source code in strands/multiagent/graph.py
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 | |
__init__()
¶
Initialize GraphBuilder with empty collections.
Source code in strands/multiagent/graph.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
add_edge(from_node, to_node, condition=None)
¶
Add an edge between two nodes with optional condition function that receives full GraphState.
Source code in strands/multiagent/graph.py
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 | |
add_node(executor, node_id=None)
¶
Add an Agent or MultiAgentBase instance as a node to the graph.
Source code in strands/multiagent/graph.py
244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
build()
¶
Build and validate the graph with configured settings.
Source code in strands/multiagent/graph.py
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 | |
reset_on_revisit(enabled=True)
¶
Control whether nodes reset their state when revisited.
When enabled, nodes will reset their messages and state to initial values each time they are revisited (re-executed). This is useful for stateless behavior where nodes should start fresh on each revisit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enabled
|
bool
|
Whether to reset node state when revisited (default: True) |
True
|
Source code in strands/multiagent/graph.py
293 294 295 296 297 298 299 300 301 302 303 304 | |
set_entry_point(node_id)
¶
Set a node as an entry point for graph execution.
Source code in strands/multiagent/graph.py
286 287 288 289 290 291 | |
set_execution_timeout(timeout)
¶
Set total execution timeout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
Total execution timeout in seconds (None for no limit) |
required |
Source code in strands/multiagent/graph.py
315 316 317 318 319 320 321 322 | |
set_graph_id(graph_id)
¶
Set graph id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph_id
|
str
|
Unique graph id |
required |
Source code in strands/multiagent/graph.py
333 334 335 336 337 338 339 340 | |
set_hook_providers(hooks)
¶
Set hook providers for the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hooks
|
list[HookProvider]
|
Customer hooks user passes in |
required |
Source code in strands/multiagent/graph.py
351 352 353 354 355 356 357 358 | |
set_max_node_executions(max_executions)
¶
Set maximum number of node executions allowed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_executions
|
int
|
Maximum total node executions (None for no limit) |
required |
Source code in strands/multiagent/graph.py
306 307 308 309 310 311 312 313 | |
set_node_timeout(timeout)
¶
Set individual node execution timeout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
Individual node timeout in seconds (None for no limit) |
required |
Source code in strands/multiagent/graph.py
324 325 326 327 328 329 330 331 | |
set_session_manager(session_manager)
¶
Set session manager for the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_manager
|
SessionManager
|
SessionManager instance |
required |
Source code in strands/multiagent/graph.py
342 343 344 345 346 347 348 349 | |
GraphEdge
dataclass
¶
Represents an edge in the graph with an optional condition.
Source code in strands/multiagent/graph.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | |
__hash__()
¶
Return hash for GraphEdge based on from_node and to_node.
Source code in strands/multiagent/graph.py
138 139 140 | |
should_traverse(state)
¶
Check if this edge should be traversed based on condition.
Source code in strands/multiagent/graph.py
142 143 144 145 146 | |
GraphNode
dataclass
¶
Represents a node in the graph.
The execution_status tracks the node's lifecycle within graph orchestration: - PENDING: Node hasn't started executing yet - EXECUTING: Node is currently running - COMPLETED/FAILED: Node finished executing (regardless of result quality)
Source code in strands/multiagent/graph.py
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 | |
__eq__(other)
¶
Return equality for GraphNode based on node_id.
Source code in strands/multiagent/graph.py
197 198 199 200 201 | |
__hash__()
¶
Return hash for GraphNode based on node_id.
Source code in strands/multiagent/graph.py
193 194 195 | |
__post_init__()
¶
Capture initial executor state after initialization.
Source code in strands/multiagent/graph.py
168 169 170 171 172 173 174 175 | |
reset_executor_state()
¶
Reset GraphNode executor state to initial state when graph was created.
This is useful when nodes are executed multiple times and need to start fresh on each execution, providing stateless behavior.
Source code in strands/multiagent/graph.py
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | |
GraphResult
dataclass
¶
Bases: MultiAgentResult
Result from graph execution - extends MultiAgentResult with graph-specific details.
Source code in strands/multiagent/graph.py
118 119 120 121 122 123 124 125 126 127 | |
GraphState
dataclass
¶
Graph execution state.
Attributes:
| Name | Type | Description |
|---|---|---|
status |
Status
|
Current execution status of the graph. |
completed_nodes |
set[GraphNode]
|
Set of nodes that have completed execution. |
failed_nodes |
set[GraphNode]
|
Set of nodes that failed during execution. |
execution_order |
list[GraphNode]
|
List of nodes in the order they were executed. |
task |
MultiAgentInput
|
The original input prompt/query provided to the graph execution. This represents the actual work to be performed by the graph as a whole. Entry point nodes receive this task as their input if they have no dependencies. |
Source code in strands/multiagent/graph.py
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 | |
should_continue(max_node_executions, execution_timeout)
¶
Check if the graph should continue execution.
Returns: (should_continue, reason)
Source code in strands/multiagent/graph.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
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 | |
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 | |
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 | |
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 | |
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 | |
_validate_node_executor(executor, existing_nodes=None)
¶
Validate a node executor for graph compatibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
executor
|
Agent | MultiAgentBase
|
The executor to validate |
required |
existing_nodes
|
dict[str, GraphNode] | None
|
Optional dict of existing nodes to check for duplicates |
None
|
Source code in strands/multiagent/graph.py
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | |
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 | |