strands.agent.agent
¶
Agent Interface.
This module implements the core Agent class that serves as the primary entry point for interacting with foundation models and tools in the SDK.
The Agent interface supports two complementary interaction patterns:
- Natural language for conversation:
agent("Analyze this data") - Method-style for direct tool access:
agent.tool.tool_name(param1="value")
AgentInput = str | list[ContentBlock] | list[InterruptResponseContent] | Messages | None
module-attribute
¶
AgentState = JSONSerializableDict
module-attribute
¶
AttributeValue = str | bool | float | int | list[str] | list[bool] | list[float] | list[int] | Sequence[str] | Sequence[bool] | Sequence[int] | Sequence[float]
module-attribute
¶
INITIAL_DELAY = 4
module-attribute
¶
MAX_ATTEMPTS = 6
module-attribute
¶
MAX_DELAY = 240
module-attribute
¶
Messages = list[Message]
module-attribute
¶
A list of messages representing a conversation.
T = TypeVar('T', bound=BaseModel)
module-attribute
¶
_DEFAULT_AGENT_ID = 'default'
module-attribute
¶
_DEFAULT_AGENT_NAME = 'Strands Agents'
module-attribute
¶
_DEFAULT_CALLBACK_HANDLER = _DefaultCallbackHandlerSentinel()
module-attribute
¶
_DEFAULT_RETRY_STRATEGY = _DefaultRetryStrategySentinel()
module-attribute
¶
logger = logging.getLogger(__name__)
module-attribute
¶
AfterInvocationEvent
dataclass
¶
Bases: HookEvent
Event triggered at the end of an agent request.
This event is fired after the agent has completed processing a request, regardless of whether it completed successfully or encountered an error. Hook providers can use this event for cleanup, logging, or state persistence.
Note: This event uses reverse callback ordering, meaning callbacks registered later will be invoked first during cleanup.
This event is triggered at the end of the following api calls
- Agent.call
- Agent.stream_async
- Agent.structured_output
Attributes:
| Name | Type | Description |
|---|---|---|
invocation_state |
dict[str, Any]
|
State and configuration passed through the agent invocation. This can include shared context for multi-agent coordination, request tracking, and dynamic configuration. |
result |
AgentResult | None
|
The result of the agent invocation, if available. This will be None when invoked from structured_output methods, as those return typed output directly rather than AgentResult. |
Source code in strands/hooks/events.py
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 | |
should_reverse_callbacks
property
¶
True to invoke callbacks in reverse order.
Agent
¶
Bases: AgentBase
Core Agent implementation.
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
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 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 | |
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, structured_output_prompt=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
|
structured_output_prompt
|
str | None
|
Custom prompt for forcing 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
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 | |
__del__()
¶
Clean up resources when agent is garbage collected.
Source code in strands/agent/agent.py
570 571 572 573 574 575 | |
__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, structured_output_prompt=None, tool_executor=None, retry_strategy=_DEFAULT_RETRY_STRATEGY)
¶
Initialize the Agent with the specified configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
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
|
Messages | None
|
List of initial messages to pre-load into the conversation. Defaults to an empty list if None. |
None
|
tools
|
list[Union[str, dict[str, str], ToolProvider, Any]] | None
|
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
|
str | list[SystemContentBlock] | None
|
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
|
type[BaseModel] | None
|
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
|
Callable[..., Any] | _DefaultCallbackHandlerSentinel | None
|
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
|
ConversationManager | None
|
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
|
Mapping[str, AttributeValue] | None
|
Custom trace attributes to apply to the agent's trace span. |
None
|
agent_id
|
str | None
|
Optional ID for the agent, useful for session management and multi-agent scenarios. Defaults to "default". |
None
|
name
|
str | None
|
name of the Agent Defaults to "Strands Agents". |
None
|
description
|
str | None
|
description of what the Agent does Defaults to None. |
None
|
state
|
AgentState | dict | None
|
stateful information for the agent. Can be either an AgentState object, or a json serializable dict. Defaults to an empty AgentState object. |
None
|
hooks
|
list[HookProvider] | None
|
hooks to be added to the agent hook registry Defaults to None. |
None
|
session_manager
|
SessionManager | None
|
Manager for handling agent sessions including conversation history and state. If provided, enables session-based persistence and state management. |
None
|
structured_output_prompt
|
str | None
|
Custom prompt message used when forcing structured output. When using structured output, if the model doesn't automatically use the output tool, the agent sends a follow-up message to request structured formatting. This parameter allows customizing that message. Defaults to "You must format the previous response as structured output." |
None
|
tool_executor
|
ToolExecutor | None
|
Definition of tool execution strategy (e.g., sequential, concurrent, etc.). |
None
|
retry_strategy
|
ModelRetryStrategy | _DefaultRetryStrategySentinel | None
|
Strategy for retrying model calls on throttling or other transient errors. Defaults to ModelRetryStrategy with max_attempts=6, initial_delay=4s, max_delay=240s. Implement a custom HookProvider for custom retry logic, or pass None to disable retries. |
_DEFAULT_RETRY_STRATEGY
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If agent id contains path separators. |
Source code in strands/agent/agent.py
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 | |
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
558 559 560 561 562 563 564 565 566 567 568 | |
invoke_async(prompt=None, *, invocation_state=None, structured_output_model=None, structured_output_prompt=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
|
structured_output_prompt
|
str | None
|
Custom prompt for forcing 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
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 | |
stream_async(prompt=None, *, invocation_state=None, structured_output_model=None, structured_output_prompt=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
|
structured_output_prompt
|
str | None
|
Custom prompt for forcing 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 |
|---|---|
ConcurrencyException
|
If another invocation is already in progress on this agent instance. |
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
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 | |
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
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 | |
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
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 | |
AgentBase
¶
Bases: Protocol
Protocol defining the interface for all agent types in Strands.
This protocol defines the minimal contract that all agent implementations must satisfy.
Source code in strands/agent/base.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | |
__call__(prompt=None, **kwargs)
¶
Synchronously invoke the agent with the given prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
AgentInput
|
Input to the agent. |
None
|
**kwargs
|
Any
|
Additional arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
AgentResult
|
AgentResult containing the agent's response. |
Source code in strands/agent/base.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
invoke_async(prompt=None, **kwargs)
async
¶
Asynchronously invoke the agent with the given prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
AgentInput
|
Input to the agent. |
None
|
**kwargs
|
Any
|
Additional arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
AgentResult
|
AgentResult containing the agent's response. |
Source code in strands/agent/base.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | |
stream_async(prompt=None, **kwargs)
¶
Stream agent execution asynchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
AgentInput
|
Input to the agent. |
None
|
**kwargs
|
Any
|
Additional arguments. |
{}
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[Any]
|
Events representing the streaming execution. |
Source code in strands/agent/base.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | |
AgentInitializedEvent
dataclass
¶
Bases: HookEvent
Event triggered when an agent has finished initialization.
This event is fired after the agent has been fully constructed and all built-in components have been initialized. Hook providers can use this event to perform setup tasks that require a fully initialized agent.
Source code in strands/hooks/events.py
25 26 27 28 29 30 31 32 33 34 | |
AgentResult
dataclass
¶
Represents the last result of invoking an agent with a prompt.
Attributes:
| Name | Type | Description |
|---|---|---|
stop_reason |
StopReason
|
The reason why the agent's processing stopped. |
message |
Message
|
The last message generated by the agent. |
metrics |
EventLoopMetrics
|
Performance metrics collected during processing. |
state |
Any
|
Additional state information from the event loop. |
interrupts |
Sequence[Interrupt] | None
|
List of interrupts if raised by user. |
structured_output |
BaseModel | None
|
Parsed structured output when structured_output_model was specified. |
Source code in strands/agent/agent_result.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
__str__()
¶
Return a string representation of the agent result.
Priority order: 1. Interrupts (if present) → stringified list of interrupt dicts 2. Structured output (if present) → JSON string 3. Text content from message → concatenated text blocks
Returns:
| Type | Description |
|---|---|
str
|
String representation based on the priority order above. |
Source code in strands/agent/agent_result.py
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 | |
from_dict(data)
classmethod
¶
Rehydrate an AgentResult from persisted JSON.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dictionary containing the serialized AgentResult data |
required |
Returns: AgentResult instance Raises: TypeError: If the data format is invalid@
Source code in strands/agent/agent_result.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | |
to_dict()
¶
Convert this AgentResult to JSON-serializable dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing serialized AgentResult data |
Source code in strands/agent/agent_result.py
89 90 91 92 93 94 95 96 97 98 99 | |
AgentResultEvent
¶
Bases: TypedEvent
Source code in strands/types/_events.py
412 413 414 | |
BedrockModel
¶
Bases: Model
AWS Bedrock model provider implementation.
The implementation handles Bedrock-specific features such as:
- Tool configuration for function calling
- Guardrails integration
- Caching points for system prompts and tools
- Streaming responses
- Context window overflow detection
Source code in strands/models/bedrock.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 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 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 | |
BedrockConfig
¶
Bases: TypedDict
Configuration options for Bedrock models.
Attributes:
| Name | Type | Description |
|---|---|---|
additional_args |
dict[str, Any] | None
|
Any additional arguments to include in the request |
additional_request_fields |
dict[str, Any] | None
|
Additional fields to include in the Bedrock request |
additional_response_field_paths |
list[str] | None
|
Additional response field paths to extract |
cache_prompt |
str | None
|
Cache point type for the system prompt (deprecated, use cache_config) |
cache_config |
CacheConfig | None
|
Configuration for prompt caching. Use CacheConfig(strategy="auto") for automatic caching. |
cache_tools |
str | None
|
Cache point type for tools |
guardrail_id |
str | None
|
ID of the guardrail to apply |
guardrail_trace |
Literal['enabled', 'disabled', 'enabled_full'] | None
|
Guardrail trace mode. Defaults to enabled. |
guardrail_version |
str | None
|
Version of the guardrail to apply |
guardrail_stream_processing_mode |
Literal['sync', 'async'] | None
|
The guardrail processing mode |
guardrail_redact_input |
bool | None
|
Flag to redact input if a guardrail is triggered. Defaults to True. |
guardrail_redact_input_message |
str | None
|
If a Bedrock Input guardrail triggers, replace the input with this message. |
guardrail_redact_output |
bool | None
|
Flag to redact output if guardrail is triggered. Defaults to False. |
guardrail_redact_output_message |
str | None
|
If a Bedrock Output guardrail triggers, replace output with this message. |
guardrail_latest_message |
bool | None
|
Flag to send only the lastest user message to guardrails. Defaults to False. |
max_tokens |
int | None
|
Maximum number of tokens to generate in the response |
model_id |
str
|
The Bedrock model ID (e.g., "us.anthropic.claude-sonnet-4-20250514-v1:0") |
include_tool_result_status |
Literal['auto'] | bool | None
|
Flag to include status field in tool results. True includes status, False removes status, "auto" determines based on model_id. Defaults to "auto". |
stop_sequences |
list[str] | None
|
List of sequences that will stop generation when encountered |
streaming |
bool | None
|
Flag to enable/disable streaming. Defaults to True. |
temperature |
float | None
|
Controls randomness in generation (higher = more random) |
top_p |
float | None
|
Controls diversity via nucleus sampling (alternative to temperature) |
Source code in strands/models/bedrock.py
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 | |
__init__(*, boto_session=None, boto_client_config=None, region_name=None, endpoint_url=None, **model_config)
¶
Initialize provider instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
boto_session
|
Session | None
|
Boto Session to use when calling the Bedrock Model. |
None
|
boto_client_config
|
Config | None
|
Configuration to use when creating the Bedrock-Runtime Boto Client. |
None
|
region_name
|
str | None
|
AWS region to use for the Bedrock service. Defaults to the AWS_REGION environment variable if set, or "us-west-2" if not set. |
None
|
endpoint_url
|
str | None
|
Custom endpoint URL for VPC endpoints (PrivateLink) |
None
|
**model_config
|
Unpack[BedrockConfig]
|
Configuration options for the Bedrock model. |
{}
|
Source code in strands/models/bedrock.py
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 | |
get_config()
¶
Get the current Bedrock Model configuration.
Returns:
| Type | Description |
|---|---|
BedrockConfig
|
The Bedrock model configuration. |
Source code in strands/models/bedrock.py
198 199 200 201 202 203 204 205 | |
stream(messages, tool_specs=None, system_prompt=None, *, tool_choice=None, system_prompt_content=None, **kwargs)
async
¶
Stream conversation with the Bedrock model.
This method calls either the Bedrock converse_stream API or the converse API based on the streaming parameter in the configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
Messages
|
List of message objects to be processed by the model. |
required |
tool_specs
|
list[ToolSpec] | None
|
List of tool specifications to make available to the model. |
None
|
system_prompt
|
str | None
|
System prompt to provide context to the model. |
None
|
tool_choice
|
ToolChoice | None
|
Selection strategy for tool invocation. |
None
|
system_prompt_content
|
list[SystemContentBlock] | None
|
System prompt content blocks to provide context to the model. |
None
|
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[StreamEvent, None]
|
Model events. |
Raises:
| Type | Description |
|---|---|
ContextWindowOverflowException
|
If the input exceeds the model's context window. |
ModelThrottledException
|
If the model service is throttling requests. |
Source code in strands/models/bedrock.py
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 | |
structured_output(output_model, prompt, system_prompt=None, **kwargs)
async
¶
Get structured output from the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_model
|
type[T]
|
The output model to use for the agent. |
required |
prompt
|
Messages
|
The prompt messages to use for the agent. |
required |
system_prompt
|
str | None
|
System prompt to provide context to the model. |
None
|
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[dict[str, T | Any], None]
|
Model events with the last being the structured output. |
Source code in strands/models/bedrock.py
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 | |
update_config(**model_config)
¶
Update the Bedrock Model configuration with the provided arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**model_config
|
Unpack[BedrockConfig]
|
Configuration overrides. |
{}
|
Source code in strands/models/bedrock.py
188 189 190 191 192 193 194 195 196 | |
BeforeInvocationEvent
dataclass
¶
Bases: HookEvent
Event triggered at the beginning of a new agent request.
This event is fired before the agent begins processing a new user request, before any model inference or tool execution occurs. Hook providers can use this event to perform request-level setup, logging, or validation.
This event is triggered at the beginning of the following api calls
- Agent.call
- Agent.stream_async
- Agent.structured_output
Attributes:
| Name | Type | Description |
|---|---|---|
invocation_state |
dict[str, Any]
|
State and configuration passed through the agent invocation. This can include shared context for multi-agent coordination, request tracking, and dynamic configuration. |
messages |
Messages | None
|
The input messages for this invocation. Can be modified by hooks to redact or transform content before processing. |
Source code in strands/hooks/events.py
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 | |
ConcurrencyException
¶
Bases: Exception
Exception raised when concurrent invocations are attempted on an agent instance.
Agent instances maintain internal state that cannot be safely accessed concurrently. This exception is raised when an invocation is attempted while another invocation is already in progress on the same agent instance.
Source code in strands/types/exceptions.py
99 100 101 102 103 104 105 106 107 | |
ConcurrentToolExecutor
¶
Bases: ToolExecutor
Concurrent tool executor.
Source code in strands/tools/executors/concurrent.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
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 | |
ContextWindowOverflowException
¶
Bases: Exception
Exception raised when the context window is exceeded.
This exception is raised when the input to a model exceeds the maximum context window size that the model can handle. This typically occurs when the combined length of the conversation history, system prompt, and current message is too large for the model to process.
Source code in strands/types/exceptions.py
38 39 40 41 42 43 44 45 46 | |
ConversationManager
¶
Bases: ABC, HookProvider
Abstract base class for managing conversation history.
This class provides an interface for implementing conversation management strategies to control the size of message arrays/conversation histories, helping to:
- Manage memory usage
- Control context length
- Maintain relevant conversation state
ConversationManager implements the HookProvider protocol, allowing derived classes to register hooks for agent lifecycle events. Derived classes that override register_hooks must call the base implementation to ensure proper hook registration.
Example
class MyConversationManager(ConversationManager):
def register_hooks(self, registry: HookRegistry, **kwargs: Any) -> None:
super().register_hooks(registry, **kwargs)
# Register additional hooks here
Source code in strands/agent/conversation_manager/conversation_manager.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |
__init__()
¶
Initialize the ConversationManager.
Attributes:
| Name | Type | Description |
|---|---|---|
removed_message_count |
The messages that have been removed from the agents messages array. These represent messages provided by the user or LLM that have been removed, not messages included by the conversation manager through something like summarization. |
Source code in strands/agent/conversation_manager/conversation_manager.py
36 37 38 39 40 41 42 43 44 | |
apply_management(agent, **kwargs)
abstractmethod
¶
Applies management strategy to the provided agent.
Processes the conversation history to maintain appropriate size by modifying the messages list in-place. Implementations should handle message pruning, summarization, or other size management techniques to keep the conversation context within desired bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent
|
Agent
|
The agent whose conversation history will be manage. This list is modified in-place. |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Source code in strands/agent/conversation_manager/conversation_manager.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 | |
get_state()
¶
Get the current state of a Conversation Manager as a Json serializable dictionary.
Source code in strands/agent/conversation_manager/conversation_manager.py
78 79 80 81 82 83 | |
reduce_context(agent, e=None, **kwargs)
abstractmethod
¶
Called when the model's context window is exceeded.
This method should implement the specific strategy for reducing the window size when a context overflow occurs. It is typically called after a ContextWindowOverflowException is caught.
Implementations might use strategies such as:
- Removing the N oldest messages
- Summarizing older context
- Applying importance-based filtering
- Maintaining critical conversation markers
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent
|
Agent
|
The agent whose conversation history will be reduced. This list is modified in-place. |
required |
e
|
Exception | None
|
The exception that triggered the context reduction, if any. |
None
|
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Source code in strands/agent/conversation_manager/conversation_manager.py
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |
register_hooks(registry, **kwargs)
¶
Register hooks for agent lifecycle events.
Derived classes that override this method must call the base implementation to ensure proper hook registration chain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
HookRegistry
|
The hook registry to register callbacks with. |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Example
def register_hooks(self, registry: HookRegistry, **kwargs: Any) -> None:
super().register_hooks(registry, **kwargs)
registry.add_callback(SomeEvent, self.on_some_event)
Source code in strands/agent/conversation_manager/conversation_manager.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | |
restore_from_session(state)
¶
Restore the Conversation Manager's state from a session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict[str, Any]
|
Previous state of the conversation manager |
required |
Returns: Optional list of messages to prepend to the agents messages. By default returns None.
Source code in strands/agent/conversation_manager/conversation_manager.py
65 66 67 68 69 70 71 72 73 74 75 76 | |
EventLoopMetrics
dataclass
¶
Aggregated metrics for an event loop's execution.
Attributes:
| Name | Type | Description |
|---|---|---|
cycle_count |
int
|
Number of event loop cycles executed. |
tool_metrics |
dict[str, ToolMetrics]
|
Metrics for each tool used, keyed by tool name. |
cycle_durations |
list[float]
|
List of durations for each cycle in seconds. |
agent_invocations |
list[AgentInvocation]
|
Agent invocation metrics containing cycles and usage data. |
traces |
list[Trace]
|
List of execution traces. |
accumulated_usage |
Usage
|
Accumulated token usage across all model invocations (across all requests). |
accumulated_metrics |
Metrics
|
Accumulated performance metrics across all model invocations. |
Source code in strands/telemetry/metrics.py
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 | |
latest_agent_invocation
property
¶
Get the most recent agent invocation.
Returns:
| Type | Description |
|---|---|
AgentInvocation | None
|
The most recent AgentInvocation, or None if no invocations exist. |
add_tool_usage(tool, duration, tool_trace, success, message)
¶
Record metrics for a tool invocation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool
|
ToolUse
|
The tool that was used. |
required |
duration
|
float
|
How long the tool call took in seconds. |
required |
tool_trace
|
Trace
|
The trace object for this tool call. |
required |
success
|
bool
|
Whether the tool call was successful. |
required |
message
|
Message
|
The message associated with the tool call. |
required |
Source code in strands/telemetry/metrics.py
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 | |
end_cycle(start_time, cycle_trace, attributes=None)
¶
End the current event loop cycle and record its duration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_time
|
float
|
The timestamp when the cycle started. |
required |
cycle_trace
|
Trace
|
The trace object for this cycle. |
required |
attributes
|
dict[str, Any] | None
|
attributes of the metrics. |
None
|
Source code in strands/telemetry/metrics.py
247 248 249 250 251 252 253 254 255 256 257 258 259 260 | |
get_summary()
¶
Generate a comprehensive summary of all collected metrics.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary containing summarized metrics data. |
dict[str, Any]
|
This includes cycle statistics, tool usage, traces, and accumulated usage information. |
Source code in strands/telemetry/metrics.py
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 | |
reset_usage_metrics()
¶
Start a new agent invocation by creating a new AgentInvocation.
This should be called at the start of a new request to begin tracking a new agent invocation with fresh usage and cycle data.
Source code in strands/telemetry/metrics.py
343 344 345 346 347 348 349 | |
start_cycle(attributes)
¶
Start a new event loop cycle and create a trace for it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attributes
|
dict[str, Any]
|
attributes of the metrics, including event_loop_cycle_id. |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, Trace]
|
A tuple containing the start time and the cycle trace object. |
Source code in strands/telemetry/metrics.py
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 | |
update_metrics(metrics)
¶
Update the accumulated performance metrics with new metrics data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metrics
|
Metrics
|
The metrics data to add to the accumulated totals. |
required |
Source code in strands/telemetry/metrics.py
351 352 353 354 355 356 357 358 359 360 | |
update_usage(usage)
¶
Update the accumulated token usage with new usage data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
usage
|
Usage
|
The usage data to add to the accumulated totals. |
required |
Source code in strands/telemetry/metrics.py
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | |
EventLoopStopEvent
¶
Bases: TypedEvent
Event emitted when the agent execution completes normally.
Source code in strands/types/_events.py
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 | |
__init__(stop_reason, message, metrics, request_state, interrupts=None, structured_output=None)
¶
Initialize with the final execution results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stop_reason
|
StopReason
|
Why the agent execution stopped |
required |
message
|
Message
|
Final message from the model |
required |
metrics
|
EventLoopMetrics
|
Execution metrics and performance data |
required |
request_state
|
Any
|
Final state of the agent execution |
required |
interrupts
|
Sequence[Interrupt] | None
|
Interrupts raised by user during agent execution. |
None
|
structured_output
|
BaseModel | None
|
Optional structured output result |
None
|
Source code in strands/types/_events.py
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
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
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 | |
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
107 108 109 110 111 112 113 114 | |
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
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 | |
__init__()
¶
Initialize an empty hook registry.
Source code in strands/hooks/registry.py
156 157 158 | |
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
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
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
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
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
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 | |
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
297 298 299 300 301 302 303 304 305 306 307 308 309 | |
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
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 | |
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
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 | |
InitEventLoopEvent
¶
Bases: TypedEvent
Event emitted at the very beginning of agent execution.
This event is fired before any processing begins and provides access to the initial invocation state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
invocation_state
|
The invocation state passed into the request |
required |
Source code in strands/types/_events.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | |
__init__()
¶
Initialize the event loop initialization event.
Source code in strands/types/_events.py
66 67 68 | |
Message
¶
Bases: TypedDict
A message in a conversation with the agent.
Attributes:
| Name | Type | Description |
|---|---|---|
content |
list[ContentBlock]
|
The message content. |
role |
Role
|
The role of the message sender. |
Source code in strands/types/content.py
178 179 180 181 182 183 184 185 186 187 | |
MessageAddedEvent
dataclass
¶
Bases: HookEvent
Event triggered when a message is added to the agent's conversation.
This event is fired whenever the agent adds a new message to its internal message history, including user messages, assistant responses, and tool results. Hook providers can use this event for logging, monitoring, or implementing custom message processing logic.
Note: This event is only triggered for messages added by the framework itself, not for messages manually added by tools or external code.
Attributes:
| Name | Type | Description |
|---|---|---|
message |
Message
|
The message that was added to the conversation history. |
Source code in strands/hooks/events.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
Model
¶
Bases: ABC
Abstract base class for Agent model providers.
This class defines the interface for all model implementations in the Strands Agents SDK. It provides a standardized way to configure and process requests for different AI model providers.
Source code in strands/models/model.py
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 | |
get_config()
abstractmethod
¶
Return the model configuration.
Returns:
| Type | Description |
|---|---|
Any
|
The model's configuration. |
Source code in strands/models/model.py
49 50 51 52 53 54 55 56 57 | |
stream(messages, tool_specs=None, system_prompt=None, *, tool_choice=None, system_prompt_content=None, invocation_state=None, **kwargs)
abstractmethod
¶
Stream conversation with the model.
This method handles the full lifecycle of conversing with the model:
- Format the messages, tool specs, and configuration into a streaming request
- Send the request to the model
- Yield the formatted message chunks
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
Messages
|
List of message objects to be processed by the model. |
required |
tool_specs
|
list[ToolSpec] | None
|
List of tool specifications to make available to the model. |
None
|
system_prompt
|
str | None
|
System prompt to provide context to the model. |
None
|
tool_choice
|
ToolChoice | None
|
Selection strategy for tool invocation. |
None
|
system_prompt_content
|
list[SystemContentBlock] | None
|
System prompt content blocks for advanced features like caching. |
None
|
invocation_state
|
dict[str, Any] | None
|
Caller-provided state/context that was passed to the agent when it was invoked. |
None
|
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Yields:
| Type | Description |
|---|---|
AsyncIterable[StreamEvent]
|
Formatted message chunks from the model. |
Raises:
| Type | Description |
|---|---|
ModelThrottledException
|
When the model service is throttling requests from the client. |
Source code in strands/models/model.py
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 | |
structured_output(output_model, prompt, system_prompt=None, **kwargs)
abstractmethod
¶
Get structured output from the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_model
|
type[T]
|
The output model to use for the agent. |
required |
prompt
|
Messages
|
The prompt messages to use for the agent. |
required |
system_prompt
|
str | None
|
System prompt to provide context to the model. |
None
|
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[dict[str, T | Any], None]
|
Model events with the last being the structured output. |
Raises:
| Type | Description |
|---|---|
ValidationException
|
The response format from the model does not match the output_model |
Source code in strands/models/model.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | |
update_config(**model_config)
abstractmethod
¶
Update the model configuration with the provided arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**model_config
|
Any
|
Configuration overrides. |
{}
|
Source code in strands/models/model.py
39 40 41 42 43 44 45 46 47 | |
ModelRetryStrategy
¶
Bases: HookProvider
Default retry strategy for model throttling with exponential backoff.
Retries model calls on ModelThrottledException using exponential backoff. Delay doubles after each attempt: initial_delay, initial_delay2, initial_delay4, etc., capped at max_delay. State resets after successful calls.
With defaults (initial_delay=4, max_delay=240, max_attempts=6), delays are: 4s → 8s → 16s → 32s → 64s (5 retries before giving up on the 6th attempt).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_attempts
|
int
|
Total model attempts before re-raising the exception. |
6
|
initial_delay
|
int
|
Base delay in seconds; used for first two retries, then doubles. |
4
|
max_delay
|
int
|
Upper bound in seconds for the exponential backoff. |
240
|
Source code in strands/event_loop/_retry.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | |
__init__(*, max_attempts=6, initial_delay=4, max_delay=240)
¶
Initialize the retry strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_attempts
|
int
|
Total model attempts before re-raising the exception. Defaults to 6. |
6
|
initial_delay
|
int
|
Base delay in seconds; used for first two retries, then doubles. Defaults to 4. |
4
|
max_delay
|
int
|
Upper bound in seconds for the exponential backoff. Defaults to 240. |
240
|
Source code in strands/event_loop/_retry.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | |
register_hooks(registry, **kwargs)
¶
Register callbacks for AfterModelCallEvent and AfterInvocationEvent.
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/event_loop/_retry.py
58 59 60 61 62 63 64 65 66 | |
ModelStreamChunkEvent
¶
Bases: TypedEvent
Event emitted during model response streaming for each raw chunk.
Source code in strands/types/_events.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
__init__(chunk)
¶
Initialize with streaming delta data from the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chunk
|
StreamEvent
|
Incremental streaming data from the model response |
required |
Source code in strands/types/_events.py
105 106 107 108 109 110 111 | |
PrintingCallbackHandler
¶
Handler for streaming text output and tool invocations to stdout.
Source code in strands/handlers/callback_handler.py
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | |
__call__(**kwargs)
¶
Stream text output and tool invocations to stdout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Callback event data including: - reasoningText (Optional[str]): Reasoning text to print if provided. - data (str): Text content to stream. - complete (bool): Whether this is the final chunk of a response. - event (dict): ModelStreamChunkEvent. |
{}
|
Source code in strands/handlers/callback_handler.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | |
__init__(verbose_tool_use=True)
¶
Initialize handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
verbose_tool_use
|
bool
|
Print out verbose information about tool calls. |
True
|
Source code in strands/handlers/callback_handler.py
10 11 12 13 14 15 16 17 | |
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
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | |
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
145 146 147 148 149 150 151 152 153 154 155 156 157 | |
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
74 75 76 77 78 79 80 81 82 | |
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
93 94 95 96 97 98 99 100 | |
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
132 133 134 135 136 137 138 139 140 141 142 143 | |
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
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
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
64 65 66 67 68 69 70 71 72 | |
register_hooks(registry, **kwargs)
¶
Register hooks for persisting the agent to the session.
Source code in strands/session/session_manager.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | |
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
84 85 86 87 88 89 90 91 | |
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
159 160 161 162 163 164 165 166 167 168 169 170 | |
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
102 103 104 105 106 107 108 109 110 111 112 113 | |
SlidingWindowConversationManager
¶
Bases: ConversationManager
Implements a sliding window strategy for managing conversation history.
This class handles the logic of maintaining a conversation window that preserves tool usage pairs and avoids invalid window states.
Supports proactive management during agent loop execution via the per_turn parameter.
Source code in strands/agent/conversation_manager/sliding_window_conversation_manager.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 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 | |
__init__(window_size=40, should_truncate_results=True, *, per_turn=False)
¶
Initialize the sliding window conversation manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_size
|
int
|
Maximum number of messages to keep in the agent's history. Defaults to 40 messages. |
40
|
should_truncate_results
|
bool
|
Truncate tool results when a message is too large for the model's context window |
True
|
per_turn
|
bool | int
|
Controls when to apply message management during agent execution. - False (default): Only apply management at the end (default behavior) - True: Apply management before every model call - int (e.g., 3): Apply management before every N model calls When to use per_turn: If your agent performs many tool operations in loops (e.g., web browsing with frequent screenshots), enable per_turn to proactively manage message history and prevent the agent loop from slowing down. Start with per_turn=True and adjust to a specific frequency (e.g., per_turn=5) if needed for performance tuning. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If per_turn is 0 or a negative integer. |
Source code in strands/agent/conversation_manager/sliding_window_conversation_manager.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | |
apply_management(agent, **kwargs)
¶
Apply the sliding window to the agent's messages array to maintain a manageable history size.
This method is called after every event loop cycle to apply a sliding window if the message count exceeds the window size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent
|
Agent
|
The agent whose messages will be managed. This list is modified in-place. |
required |
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Source code in strands/agent/conversation_manager/sliding_window_conversation_manager.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
get_state()
¶
Get the current state of the conversation manager.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing the manager's state, including model call count for per-turn tracking. |
Source code in strands/agent/conversation_manager/sliding_window_conversation_manager.py
96 97 98 99 100 101 102 103 104 | |
reduce_context(agent, e=None, **kwargs)
¶
Trim the oldest messages to reduce the conversation context size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent
|
Agent
|
The agent whose messages will be reduce. This list is modified in-place. |
required |
e
|
Exception | None
|
The exception that triggered the context reduction, if any. |
None
|
**kwargs
|
Any
|
Additional keyword arguments for future extensibility. |
{}
|
Raises:
| Type | Description |
|---|---|
ContextWindowOverflowException
|
If the context cannot be reduced further. Such as when the conversation is already minimal or when tool result messages cannot be properly converted. |
Source code in strands/agent/conversation_manager/sliding_window_conversation_manager.py
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | |
register_hooks(registry, **kwargs)
¶
Register hook callbacks for per-turn conversation management.
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/agent/conversation_manager/sliding_window_conversation_manager.py
54 55 56 57 58 59 60 61 62 63 64 | |
restore_from_session(state)
¶
Restore the conversation manager's state from a session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict[str, Any]
|
Previous state of the conversation manager |
required |
Returns:
| Type | Description |
|---|---|
list | None
|
Optional list of messages to prepend to the agent's messages. |
Source code in strands/agent/conversation_manager/sliding_window_conversation_manager.py
106 107 108 109 110 111 112 113 114 115 116 117 | |
StructuredOutputContext
¶
Per-invocation context for structured output execution.
Source code in strands/tools/structured_output/_structured_output_context.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | |
is_enabled
property
¶
Check if structured output is enabled for this context.
Returns:
| Type | Description |
|---|---|
bool
|
True if a structured output model is configured, False otherwise. |
__init__(structured_output_model=None, structured_output_prompt=None)
¶
Initialize a new structured output context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structured_output_model
|
type[BaseModel] | None
|
Optional Pydantic model type for structured output. |
None
|
structured_output_prompt
|
str | None
|
Optional custom prompt message to use when forcing structured output. Defaults to "You must format the previous response as structured output." |
None
|
Source code in strands/tools/structured_output/_structured_output_context.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | |
cleanup(registry)
¶
Clean up the registered structured output tool from the registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
ToolRegistry
|
The tool registry to clean up the tool from. |
required |
Source code in strands/tools/structured_output/_structured_output_context.py
144 145 146 147 148 149 150 151 152 | |
extract_result(tool_uses)
¶
Extract and remove structured output result from stored results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_uses
|
list[ToolUse]
|
List of tool use dictionaries from the current execution cycle. |
required |
Returns:
| Type | Description |
|---|---|
BaseModel | None
|
The structured output result if found, or None if no result available. |
Source code in strands/tools/structured_output/_structured_output_context.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
get_result(tool_use_id)
¶
Retrieve a stored structured output result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_use_id
|
str
|
Unique identifier for the tool use. |
required |
Returns:
| Type | Description |
|---|---|
BaseModel | None
|
The validated Pydantic model instance, or None if not found. |
Source code in strands/tools/structured_output/_structured_output_context.py
66 67 68 69 70 71 72 73 74 75 | |
get_tool_spec()
¶
Get the tool specification for structured output.
Returns:
| Type | Description |
|---|---|
ToolSpec | None
|
Tool specification, or None if no structured output model. |
Source code in strands/tools/structured_output/_structured_output_context.py
103 104 105 106 107 108 109 110 111 | |
has_structured_output_tool(tool_uses)
¶
Check if any tool uses are for the structured output tool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_uses
|
list[ToolUse]
|
List of tool use dictionaries to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if any tool use matches the expected structured output tool name, |
bool
|
False if no structured output tool is present or expected. |
Source code in strands/tools/structured_output/_structured_output_context.py
89 90 91 92 93 94 95 96 97 98 99 100 101 | |
register_tool(registry)
¶
Register the structured output tool with the registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
ToolRegistry
|
The tool registry to register the tool with. |
required |
Source code in strands/tools/structured_output/_structured_output_context.py
134 135 136 137 138 139 140 141 142 | |
set_forced_mode(tool_choice=None)
¶
Mark this context as being in forced structured output mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_choice
|
dict | None
|
Optional tool choice configuration. |
None
|
Source code in strands/tools/structured_output/_structured_output_context.py
77 78 79 80 81 82 83 84 85 86 87 | |
store_result(tool_use_id, result)
¶
Store a validated structured output result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_use_id
|
str
|
Unique identifier for the tool use. |
required |
result
|
BaseModel
|
Validated Pydantic model instance. |
required |
Source code in strands/tools/structured_output/_structured_output_context.py
57 58 59 60 61 62 63 64 | |
SystemContentBlock
¶
Bases: TypedDict
Contains configurations for instructions to provide the model for how to handle input.
Attributes:
| Name | Type | Description |
|---|---|---|
cachePoint |
CachePoint
|
A cache point configuration to optimize conversation history. |
text |
str
|
A system prompt for the model. |
Source code in strands/types/content.py
102 103 104 105 106 107 108 109 110 111 | |
ToolExecutor
¶
Bases: ABC
Abstract base class for tool executors.
Source code in strands/tools/executors/_executor.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 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 | |
ToolProvider
¶
Bases: ABC
Interface for providing tools with lifecycle management.
Provides a way to load a collection of tools and clean them up when done, with lifecycle managed by the agent.
Source code in strands/tools/tool_provider.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | |
add_consumer(consumer_id, **kwargs)
abstractmethod
¶
Add a consumer to this tool provider.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
consumer_id
|
Any
|
Unique identifier for the consumer. |
required |
**kwargs
|
Any
|
Additional arguments for future compatibility. |
{}
|
Source code in strands/tools/tool_provider.py
30 31 32 33 34 35 36 37 38 | |
load_tools(**kwargs)
abstractmethod
async
¶
Load and return the tools in this provider.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Additional arguments for future compatibility. |
{}
|
Returns:
| Type | Description |
|---|---|
Sequence[AgentTool]
|
List of tools that are ready to use. |
Source code in strands/tools/tool_provider.py
18 19 20 21 22 23 24 25 26 27 28 | |
remove_consumer(consumer_id, **kwargs)
abstractmethod
¶
Remove a consumer from this tool provider.
This method must be idempotent - calling it multiple times with the same ID should have no additional effect after the first call.
Provider may clean up resources when no consumers remain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
consumer_id
|
Any
|
Unique identifier for the consumer. |
required |
**kwargs
|
Any
|
Additional arguments for future compatibility. |
{}
|
Source code in strands/tools/tool_provider.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 | |
ToolRegistry
¶
Central registry for all tools available to the agent.
This class manages tool registration, validation, discovery, and invocation.
Source code in strands/tools/registry.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 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 | |
NewToolDict
¶
Bases: TypedDict
Dictionary type for adding or updating a tool in the configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
spec |
ToolSpec
|
The tool specification that defines the tool's interface and behavior. |
Source code in strands/tools/registry.py
640 641 642 643 644 645 646 647 | |
__init__()
¶
Initialize the tool registry.
Source code in strands/tools/registry.py
37 38 39 40 41 42 43 | |
cleanup(**kwargs)
¶
Synchronously clean up all tool providers in this registry.
Source code in strands/tools/registry.py
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 | |
discover_tool_modules()
¶
Discover available tool modules in all tools directories.
Returns:
| Type | Description |
|---|---|
dict[str, Path]
|
Dictionary mapping tool names to their full paths. |
Source code in strands/tools/registry.py
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 | |
get_all_tool_specs()
¶
Get all the tool specs for all tools in this registry..
Returns:
| Type | Description |
|---|---|
list[ToolSpec]
|
A list of ToolSpecs. |
Source code in strands/tools/registry.py
565 566 567 568 569 570 571 572 573 | |
get_all_tools_config()
¶
Dynamically generate tool configuration by combining built-in and dynamic tools.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing all tool configurations. |
Source code in strands/tools/registry.py
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 | |
get_tools_dirs()
¶
Get all tool directory paths.
Returns:
| Type | Description |
|---|---|
list[Path]
|
A list of Path objects for current working directory's "./tools/". |
Source code in strands/tools/registry.py
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | |
initialize_tools(load_tools_from_directory=False)
¶
Initialize all tools by discovering and loading them dynamically from all tool directories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
load_tools_from_directory
|
bool
|
Whether to reload tools if changes are made at runtime. |
False
|
Source code in strands/tools/registry.py
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 | |
load_tool_from_filepath(tool_name, tool_path)
¶
DEPRECATED: Load a tool from a file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_name
|
str
|
Name of the tool. |
required |
tool_path
|
str
|
Path to the tool file. |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the tool file is not found. |
ValueError
|
If the tool cannot be loaded. |
Source code in strands/tools/registry.py
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 | |
process_tools(tools)
¶
Process tools list.
Process list of tools that can contain local file path string, module import path string, imported modules, @tool decorated functions, or instances of AgentTool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tools
|
list[Any]
|
List of tool specifications. Can be:
|
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of tool names that were processed. |
Source code in strands/tools/registry.py
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 | |
register_dynamic_tool(tool)
¶
Register a tool dynamically for temporary use.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool
|
AgentTool
|
The tool to register dynamically |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a tool with this name already exists |
Source code in strands/tools/registry.py
575 576 577 578 579 580 581 582 583 584 585 586 587 588 | |
register_tool(tool)
¶
Register a tool function with the given name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool
|
AgentTool
|
The tool to register. |
required |
Source code in strands/tools/registry.py
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 | |
reload_tool(tool_name)
¶
Reload a specific tool module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_name
|
str
|
Name of the tool to reload. |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the tool file cannot be found. |
ImportError
|
If there are issues importing the tool module. |
ValueError
|
If the tool specification is invalid or required components are missing. |
Exception
|
For other errors during tool reloading. |
Source code in strands/tools/registry.py
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 | |
replace(new_tool)
¶
Replace an existing tool with a new implementation.
This performs a swap of the tool implementation in the registry. The replacement takes effect on the next agent invocation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_tool
|
AgentTool
|
New tool implementation. Its name must match the tool being replaced. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the tool doesn't exist. |
Source code in strands/tools/registry.py
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 | |
validate_tool_spec(tool_spec)
¶
Validate tool specification against required schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_spec
|
ToolSpec
|
Tool specification to validate. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the specification is invalid. |
Source code in strands/tools/registry.py
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 | |
ToolWatcher
¶
Watches tool directories for changes and reloads tools when they are modified.
Source code in strands/tools/watcher.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | |
MasterChangeHandler
¶
Bases: FileSystemEventHandler
Master handler that delegates to all registered handlers.
Source code in strands/tools/watcher.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 | |
__init__(dir_path)
¶
Initialize a master change handler for a specific directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dir_path
|
str
|
The directory path to watch. |
required |
Source code in strands/tools/watcher.py
72 73 74 75 76 77 78 | |
on_modified(event)
¶
Delegate file modification events to all registered handlers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
Any
|
The file system event that triggered this handler. |
required |
Source code in strands/tools/watcher.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | |
ToolChangeHandler
¶
Bases: FileSystemEventHandler
Handler for tool file changes.
Source code in strands/tools/watcher.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 | |
__init__(tool_registry)
¶
Initialize a tool change handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_registry
|
ToolRegistry
|
The tool registry to update when tools change. |
required |
Source code in strands/tools/watcher.py
44 45 46 47 48 49 50 | |
on_modified(event)
¶
Reload tool if file modification detected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
Any
|
The file system event that triggered this handler. |
required |
Source code in strands/tools/watcher.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | |
__init__(tool_registry)
¶
Initialize a tool watcher for the given tool registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_registry
|
ToolRegistry
|
The tool registry to report changes. |
required |
Source code in strands/tools/watcher.py
32 33 34 35 36 37 38 39 | |
start()
¶
Start watching all tools directories for changes.
Source code in strands/tools/watcher.py
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 | |
TypedEvent
¶
Bases: dict
Base class for all typed events in the agent system.
Source code in strands/types/_events.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | |
is_callback_event
property
¶
True if this event should trigger the callback_handler to fire.
__init__(data=None)
¶
Initialize the typed event with optional data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any] | None
|
Optional dictionary of event data to initialize with |
None
|
Source code in strands/types/_events.py
30 31 32 33 34 35 36 | |
as_dict()
¶
Convert this event to a raw dictionary for emitting purposes.
Source code in strands/types/_events.py
43 44 45 | |
prepare(invocation_state)
¶
Prepare the event for emission by adding invocation state.
This allows a subset of events to merge with the invocation_state without needing to pass around the invocation_state throughout the system.
Source code in strands/types/_events.py
47 48 49 50 51 52 53 | |
_DefaultCallbackHandlerSentinel
¶
Sentinel class to distinguish between explicit None and default parameter value.
Source code in strands/agent/agent.py
76 77 78 79 | |
_DefaultRetryStrategySentinel
¶
Sentinel class to distinguish between explicit None and default parameter value for retry_strategy.
Source code in strands/agent/agent.py
82 83 84 85 | |
_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 | |
_ToolCaller
¶
Call tool as a function.
Source code in strands/tools/_caller.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | |
__getattr__(name)
¶
Call tool as a function.
This method enables the method-style interface (e.g., agent.tool.tool_name(param="value")).
It matches underscore-separated names to hyphenated tool names (e.g., 'some_thing' matches 'some-thing').
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the attribute (tool) being accessed. |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., Any]
|
A function that when called will execute the named tool. |
Raises:
| Type | Description |
|---|---|
AttributeError
|
If no tool with the given name exists or if multiple tools match the given name. |
Source code in strands/tools/_caller.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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
__init__(agent)
¶
Initialize instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent
|
Agent | BidiAgent
|
Agent reference that will accept tool results. |
required |
Source code in strands/tools/_caller.py
30 31 32 33 34 35 36 37 38 | |
event_loop_cycle(agent, invocation_state, structured_output_context=None)
async
¶
Execute a single cycle of the event loop.
This core function processes a single conversation turn, handling model inference, tool execution, and error recovery. It manages the entire lifecycle of a conversation turn, including:
- Initializing cycle state and metrics
- Checking execution limits
- Processing messages with the model
- Handling tool execution requests
- Managing recursive calls for multi-turn tool interactions
- Collecting and reporting metrics
- Error handling and recovery
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent
|
Agent
|
The agent for which the cycle is being executed. |
required |
invocation_state
|
dict[str, Any]
|
Additional arguments including:
|
required |
structured_output_context
|
StructuredOutputContext | None
|
Optional context for structured output management. |
None
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[TypedEvent, None]
|
Model and tool stream events. The last event is a tuple containing:
|
Raises:
| Type | Description |
|---|---|
EventLoopException
|
If an error occurs during execution |
ContextWindowOverflowException
|
If the input is too large for the model |
Source code in strands/event_loop/event_loop.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | |
generate_missing_tool_result_content(tool_use_ids)
¶
Generate ToolResult content blocks for orphaned ToolUse message.
Source code in strands/tools/_tool_helpers.py
19 20 21 22 23 24 25 26 27 28 29 30 | |
get_tracer()
¶
Get or create the global tracer.
Returns:
| Type | Description |
|---|---|
Tracer
|
The global tracer instance. |
Source code in strands/telemetry/tracer.py
880 881 882 883 884 885 886 887 888 889 890 891 | |
null_callback_handler(**_kwargs)
¶
Callback handler that discards all output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**_kwargs
|
Any
|
Event data (ignored). |
{}
|
Source code in strands/handlers/callback_handler.py
67 68 69 70 71 72 73 | |
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
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | |
serialize(obj)
¶
Serialize an object to JSON with consistent settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
The object to serialize |
required |
Returns:
| Type | Description |
|---|---|
str
|
JSON string representation of the object |
Source code in strands/telemetry/tracer.py
894 895 896 897 898 899 900 901 902 903 | |