strands.agent
¶
This package provides the core Agent interface and supporting components for building AI agents with the SDK.
It includes:
- Agent: The main interface for interacting with AI models and tools
- ConversationManager: Classes for managing conversation history and context windows
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")
Agent
¶
Core Agent interface.
An agent orchestrates the following workflow:
- Receives user input
- Processes the input using a language model
- Decides whether to use tools to gather information or perform actions
- Executes those tools and receives results
- Continues reasoning with the new information
- Produces a final response
Source code in strands/agent/agent.py
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 |
|
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_config
property
¶
Get the tool configuration for this agent.
Returns:
Type | Description |
---|---|
ToolConfig
|
The complete tool configuration. |
tool_names
property
¶
Get a list of all registered tool names.
Returns:
Type | Description |
---|---|
List[str]
|
Names of all tools available to this agent. |
ToolCaller
¶
Call tool as a function.
Source code in strands/agent/agent.py
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 |
|
__getattr__(name)
¶
Call tool as a function.
This method enables the method-style interface (e.g., agent.tool.tool_name(param="value")
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
The name of the attribute (tool) being accessed. |
required |
Returns:
Type | Description |
---|---|
Callable
|
A function that when called will execute the named tool. |
Raises:
Type | Description |
---|---|
AttributeError
|
If no tool with the given name exists. |
Source code in strands/agent/agent.py
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 |
|
__init__(agent)
¶
Initialize instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent
|
Agent
|
Agent reference that will accept tool results. |
required |
Source code in strands/agent/agent.py
63 64 65 66 67 68 69 70 71 |
|
__call__(prompt, **kwargs)
¶
Process a natural language prompt through the agent's event loop.
This method implements the conversational interface (e.g., agent("hello!")
). It adds the user's prompt to
the conversation history, processes it through the model, executes any tool calls, and returns the final result.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prompt
|
str
|
The natural language prompt from the user. |
required |
**kwargs
|
Any
|
Additional parameters to pass to the event loop. |
{}
|
Returns:
Type | Description |
---|---|
AgentResult
|
Result object containing:
|
Source code in strands/agent/agent.py
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 |
|
__del__()
¶
Clean up resources when Agent is garbage collected.
Ensures proper shutdown of the thread pool executor if one exists.
Source code in strands/agent/agent.py
304 305 306 307 308 309 310 311 |
|
__init__(model=None, messages=None, tools=None, system_prompt=None, callback_handler=PrintingCallbackHandler(), conversation_manager=None, max_parallel_tools=os.cpu_count() or 1, record_direct_tool_call=True, load_tools_from_directory=True, trace_attributes=None)
¶
Initialize the Agent with the specified configuration.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Union[Model, str, None]
|
Provider for running inference or a string representing the model-id for Bedrock to use. Defaults to strands.models.BedrockModel if None. |
None
|
messages
|
Optional[Messages]
|
List of initial messages to pre-load into the conversation. Defaults to an empty list if None. |
None
|
tools
|
Optional[List[Union[str, Dict[str, str], Any]]]
|
List of tools to make available to the agent. Can be specified as:
If provided, only these tools will be available. If None, all tools will be available. |
None
|
system_prompt
|
Optional[str]
|
System prompt to guide model behavior. If None, the model will behave according to its default settings. |
None
|
callback_handler
|
Optional[Callable]
|
Callback for processing events as they happen during agent execution. Defaults to strands.handlers.PrintingCallbackHandler if None. |
PrintingCallbackHandler()
|
conversation_manager
|
Optional[ConversationManager]
|
Manager for conversation history and context window. Defaults to strands.agent.conversation_manager.SlidingWindowConversationManager if None. |
None
|
max_parallel_tools
|
int
|
Maximum number of tools to run in parallel when the model returns multiple tool calls. Defaults to os.cpu_count() or 1. |
cpu_count() or 1
|
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 |
True
|
trace_attributes
|
Optional[Mapping[str, AttributeValue]]
|
Custom trace attributes to apply to the agent's trace span. |
None
|
Raises:
Type | Description |
---|---|
ValueError
|
If max_parallel_tools is less than 1. |
Source code in strands/agent/agent.py
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 |
|
stream_async(prompt, **kwargs)
async
¶
Process a natural language prompt and yield events as an async iterator.
This method provides an asynchronous interface for streaming agent events, allowing consumers to process stream events programmatically through an async iterator pattern rather than callback functions. This is particularly useful for web servers and other async environments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prompt
|
str
|
The natural language prompt from the user. |
required |
**kwargs
|
Any
|
Additional parameters to pass to the event loop. |
{}
|
Returns:
Type | Description |
---|---|
AsyncIterator[Any]
|
An async iterator that yields events. Each event is a dictionary containing |
AsyncIterator[Any]
|
information about the current state of processing, such as: |
AsyncIterator[Any]
|
|
AsyncIterator[Any]
|
|
AsyncIterator[Any]
|
|
AsyncIterator[Any]
|
|
Raises:
Type | Description |
---|---|
Exception
|
Any exceptions from the agent invocation will be propagated to the caller. |
Example
async for event in agent.stream_async("Analyze this data"):
if "data" in event:
yield event["data"]
Source code in strands/agent/agent.py
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 |
|
strands.agent.agent_result
¶
Agent result handling for SDK.
This module defines the AgentResult class which encapsulates the complete response from an agent's processing cycle.
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. |
Source code in strands/agent/agent_result.py
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 |
|
__str__()
¶
Get the agent's last message as a string.
This method extracts and concatenates all text content from the final message, ignoring any non-text content like images or structured data.
Returns:
Type | Description |
---|---|
str
|
The agent's last message as a string. |
Source code in strands/agent/agent_result.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
|
strands.agent.conversation_manager
¶
This package provides classes for managing conversation history during agent execution.
It includes:
- ConversationManager: Abstract base class defining the conversation management interface
- NullConversationManager: A no-op implementation that does not modify conversation history
- SlidingWindowConversationManager: An implementation that maintains a sliding window of messages to control context size while preserving conversation coherence
Conversation managers help control memory usage and context length while maintaining relevant conversation state, which is critical for effective agent interactions.
strands.agent.conversation_manager.conversation_manager
¶
Abstract interface for conversation history management.
ConversationManager
¶
Bases: ABC
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
Source code in strands/agent/conversation_manager/conversation_manager.py
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 48 49 50 51 52 53 54 55 |
|
apply_management(messages)
abstractmethod
¶
Applies management strategy to the provided list of messages.
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 |
---|---|---|---|
messages
|
Messages
|
The conversation history to manage. This list is modified in-place. |
required |
Source code in strands/agent/conversation_manager/conversation_manager.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
reduce_context(messages, e=None)
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 |
---|---|---|---|
messages
|
Messages
|
The conversation history to reduce. This list is modified in-place. |
required |
e
|
Optional[Exception]
|
The exception that triggered the context reduction, if any. |
None
|
Source code in strands/agent/conversation_manager/conversation_manager.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
|
strands.agent.conversation_manager.null_conversation_manager
¶
Null implementation of conversation management.
NullConversationManager
¶
Bases: ConversationManager
A no-op conversation manager that does not modify the conversation history.
Useful for:
- Testing scenarios where conversation management should be disabled
- Cases where conversation history is managed externally
- Situations where the full conversation history should be preserved
Source code in strands/agent/conversation_manager/null_conversation_manager.py
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 |
|
apply_management(messages)
¶
Does nothing to the conversation history.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
messages
|
Messages
|
The conversation history that will remain unmodified. |
required |
Source code in strands/agent/conversation_manager/null_conversation_manager.py
20 21 22 23 24 25 26 |
|
reduce_context(messages, e=None)
¶
Does not reduce context and raises an exception.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
messages
|
Messages
|
The conversation history that will remain unmodified. |
required |
e
|
Optional[Exception]
|
The exception that triggered the context reduction, if any. |
None
|
Raises:
Type | Description |
---|---|
e
|
If provided. |
ContextWindowOverflowException
|
If e is None. |
Source code in strands/agent/conversation_manager/null_conversation_manager.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
strands.agent.conversation_manager.sliding_window_conversation_manager
¶
Sliding window conversation history management.
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.
Source code in strands/agent/conversation_manager/sliding_window_conversation_manager.py
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 |
|
__init__(window_size=40)
¶
Initialize the sliding window conversation manager.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
window_size
|
int
|
Maximum number of messages to keep in history. Defaults to 40 messages. |
40
|
Source code in strands/agent/conversation_manager/sliding_window_conversation_manager.py
46 47 48 49 50 51 52 53 |
|
apply_management(messages)
¶
Apply the sliding window to the messages array to maintain a manageable history size.
This method is called after every event loop cycle, as the messages array may have been modified with tool results and assistant responses. It first removes any dangling messages that might create an invalid conversation state, then applies the sliding window if the message count exceeds the window size.
Special handling is implemented to ensure we don't leave a user message with toolResult as the first message in the array. It also ensures that all toolUse blocks have corresponding toolResult blocks to maintain conversation coherence.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
messages
|
Messages
|
The messages to manage. This list is modified in-place. |
required |
Source code in strands/agent/conversation_manager/sliding_window_conversation_manager.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
|
reduce_context(messages, e=None)
¶
Trim the oldest messages to reduce the conversation context size.
The method handles special cases where tool results need to be converted to regular content blocks to maintain conversation coherence after trimming.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
messages
|
Messages
|
The messages to reduce. This list is modified in-place. |
required |
e
|
Optional[Exception]
|
The exception that triggered the context reduction, if any. |
None
|
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
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 |
|
is_assistant_message(message)
¶
Check if a message is from an assistant.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
Message
|
The message object to check. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the message has the assistant role, False otherwise. |
Source code in strands/agent/conversation_manager/sliding_window_conversation_manager.py
27 28 29 30 31 32 33 34 35 36 |
|
is_user_message(message)
¶
Check if a message is from a user.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
Message
|
The message object to check. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the message has the user role, False otherwise. |
Source code in strands/agent/conversation_manager/sliding_window_conversation_manager.py
15 16 17 18 19 20 21 22 23 24 |
|