strands.event_loop
¶
This package provides the core event loop implementation for the agents SDK.
The event loop enables conversational AI agents to process messages, execute tools, and handle errors in a controlled, iterative manner.
strands.event_loop.event_loop
¶
This module implements the central event loop.
The event loop allows agents to:
- Process conversation messages
- Execute tools based on model requests
- Handle errors and recovery strategies
- Manage recursive execution cycles
event_loop_cycle(model, system_prompt, messages, tool_config, callback_handler, tool_handler, tool_execution_handler=None, **kwargs)
¶
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 |
---|---|---|---|
model
|
Model
|
Provider for running model inference. |
required |
system_prompt
|
Optional[str]
|
System prompt instructions for the model. |
required |
messages
|
Messages
|
Conversation history messages. |
required |
tool_config
|
Optional[ToolConfig]
|
Configuration for available tools. |
required |
callback_handler
|
Callable[..., Any]
|
Callback for processing events as they happen. |
required |
tool_handler
|
Optional[ToolHandler]
|
Handler for executing tools. |
required |
tool_execution_handler
|
Optional[ParallelToolExecutorInterface]
|
Optional handler for parallel tool execution. |
None
|
**kwargs
|
Any
|
Additional arguments including:
|
{}
|
Returns:
Type | Description |
---|---|
Tuple[StopReason, Message, EventLoopMetrics, Any]
|
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
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 |
|
recurse_event_loop(**kwargs)
¶
Make a recursive call to event_loop_cycle with the current state.
This function is used when the event loop needs to continue processing after tool execution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**kwargs
|
Any
|
Arguments to pass to event_loop_cycle, including:
|
{}
|
Returns:
Type | Description |
---|---|
Tuple[StopReason, Message, EventLoopMetrics, Any]
|
Results from event_loop_cycle:
|
Source code in strands/event_loop/event_loop.py
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 |
|
strands.event_loop.error_handler
¶
This module provides specialized error handlers for common issues that may occur during event loop execution.
Examples include throttling exceptions and context window overflow errors. These handlers implement recovery strategies like exponential backoff for throttling and message truncation for context window limitations.
handle_throttling_error(e, attempt, max_attempts, current_delay, max_delay, callback_handler, kwargs)
¶
Handle throttling exceptions from the model provider with exponential backoff.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
e
|
ModelThrottledException
|
The exception that occurred during model invocation. |
required |
attempt
|
int
|
Number of times event loop has attempted model invocation. |
required |
max_attempts
|
int
|
Maximum number of retry attempts allowed. |
required |
current_delay
|
int
|
Current delay in seconds before retrying. |
required |
max_delay
|
int
|
Maximum delay in seconds (cap for exponential growth). |
required |
callback_handler
|
Any
|
Callback for processing events as they happen. |
required |
kwargs
|
Dict[str, Any]
|
Additional arguments to pass to the callback handler. |
required |
Returns:
Type | Description |
---|---|
Tuple[bool, int]
|
A tuple containing: - bool: True if retry should be attempted, False otherwise - int: The new delay to use for the next retry attempt |
Source code in strands/event_loop/error_handler.py
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 |
|
strands.event_loop.message_processor
¶
This module provides utilities for processing and manipulating conversation messages within the event loop.
It includes functions for cleaning up orphaned tool uses, finding messages with specific content types, and truncating large tool results to prevent context window overflow.
clean_orphaned_empty_tool_uses(messages)
¶
Clean up orphaned empty tool uses in conversation messages.
This function identifies and removes any toolUse entries with empty input that don't have a corresponding toolResult. This prevents validation errors that occur when the model expects matching toolResult blocks for each toolUse.
The function applies fixes by either:
- Replacing a message containing only an orphaned toolUse with a context message
- Removing the orphaned toolUse entry from a message with multiple content items
Parameters:
Name | Type | Description | Default |
---|---|---|---|
messages
|
Messages
|
The conversation message history. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if any fixes were applied, False otherwise. |
Source code in strands/event_loop/message_processor.py
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 |
|
strands.event_loop.streaming
¶
Utilities for handling streaming responses from language models.
extract_usage_metrics(event)
¶
Extracts usage metrics from the metadata chunk.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
MetadataEvent
|
metadata. |
required |
Returns:
Type | Description |
---|---|
tuple[Usage, Metrics]
|
The extracted usage metrics and latency. |
Source code in strands/event_loop/streaming.py
239 240 241 242 243 244 245 246 247 248 249 250 251 |
|
handle_content_block_delta(event, state)
¶
Handles content block delta updates by appending text, tool input, or reasoning content to the state.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
ContentBlockDeltaEvent
|
Delta event. |
required |
state
|
dict[str, Any]
|
The current state of message processing. |
required |
Returns:
Type | Description |
---|---|
tuple[dict[str, Any], dict[str, Any]]
|
Updated state with appended text or tool input. |
Source code in strands/event_loop/streaming.py
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 |
|
handle_content_block_start(event)
¶
Handles the start of a content block by extracting tool usage information if any.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
ContentBlockStartEvent
|
Start event. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Dictionary with tool use id and name if tool use request, empty dictionary otherwise. |
Source code in strands/event_loop/streaming.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
|
handle_content_block_stop(state)
¶
Handles the end of a content block by finalizing tool usage, text content, or reasoning content.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
dict[str, Any]
|
The current state of message processing. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
Updated state with finalized content block. |
Source code in strands/event_loop/streaming.py
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 |
|
handle_message_start(event, message)
¶
Handles the start of a message by setting the role in the message dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
MessageStartEvent
|
A message start event. |
required |
message
|
Message
|
The message dictionary being constructed. |
required |
Returns:
Type | Description |
---|---|
Message
|
Updated message dictionary with the role set. |
Source code in strands/event_loop/streaming.py
69 70 71 72 73 74 75 76 77 78 79 80 |
|
handle_message_stop(event)
¶
Handles the end of a message by returning the stop reason.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
MessageStopEvent
|
Stop event. |
required |
Returns:
Type | Description |
---|---|
StopReason
|
The reason for stopping the stream. |
Source code in strands/event_loop/streaming.py
212 213 214 215 216 217 218 219 220 221 |
|
handle_redact_content(event, messages, state)
¶
Handles redacting content from the input or output.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
RedactContentEvent
|
Redact Content Event. |
required |
messages
|
Messages
|
Agent messages. |
required |
state
|
dict[str, Any]
|
The current state of message processing. |
required |
Source code in strands/event_loop/streaming.py
224 225 226 227 228 229 230 231 232 233 234 235 236 |
|
process_stream(chunks, messages)
¶
Processes the response stream from the API, constructing the final message and extracting usage metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
chunks
|
Iterable[StreamEvent]
|
The chunks of the response stream from the model. |
required |
messages
|
Messages
|
The agents messages. |
required |
Returns:
Type | Description |
---|---|
None
|
The reason for stopping, the constructed message, and the usage metrics. |
Source code in strands/event_loop/streaming.py
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 |
|
remove_blank_messages_content_text(messages)
¶
Remove or replace blank text in message content.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
messages
|
Messages
|
Conversation messages to update. |
required |
Returns:
Type | Description |
---|---|
Messages
|
Updated messages. |
Source code in strands/event_loop/streaming.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 |
|
stream_messages(model, system_prompt, messages, tool_config)
¶
Streams messages to the model and processes the response.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Model
|
Model provider. |
required |
system_prompt
|
Optional[str]
|
The system prompt to send. |
required |
messages
|
Messages
|
List of messages to send. |
required |
tool_config
|
Optional[ToolConfig]
|
Configuration for the tools to use. |
required |
Returns:
Type | Description |
---|---|
None
|
The reason for stopping, the final message, and the usage metrics |
Source code in strands/event_loop/streaming.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 |
|