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
|
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
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 |
|
initialize_state(**kwargs)
¶
Initialize the request state if not present.
Creates an empty request_state dictionary if one doesn't already exist in the provided keyword arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**kwargs
|
Any
|
Keyword arguments that may contain a request_state. |
{}
|
Returns:
Type | Description |
---|---|
Any
|
The updated kwargs dictionary with request_state initialized if needed. |
Source code in strands/event_loop/event_loop.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
|
prepare_next_cycle(kwargs, event_loop_metrics)
¶
Prepare state for the next event loop cycle.
Updates the keyword arguments with the current event loop metrics and stores the current cycle ID as the parent cycle ID for the next cycle. This maintains the parent-child relationship between cycles for tracing and metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
kwargs
|
Dict[str, Any]
|
Current keyword arguments containing event loop state. |
required |
event_loop_metrics
|
EventLoopMetrics
|
The metrics object tracking event loop execution. |
required |
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
Updated keyword arguments ready for the next cycle. |
Source code in strands/event_loop/event_loop.py
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
|
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
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 |
|
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_input_too_long_error(e, messages, model, system_prompt, tool_config, callback_handler, tool_handler, kwargs)
¶
Handle 'Input is too long' errors by truncating tool results.
When a context window overflow exception occurs (input too long for the model), this function attempts to recover by finding and truncating the most recent tool results in the conversation history. If trunction is successful, the function will make a call to the event loop.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
e
|
ContextWindowOverflowException
|
The ContextWindowOverflowException that occurred. |
required |
messages
|
Messages
|
The conversation message history. |
required |
model
|
Model
|
Model provider for running inference. |
required |
system_prompt
|
Optional[str]
|
System prompt for the model. |
required |
tool_config
|
Any
|
Tool configuration for the conversation. |
required |
callback_handler
|
Any
|
Callback for processing events as they happen. |
required |
tool_handler
|
Any
|
Handler for tool execution. |
required |
kwargs
|
Dict[str, Any]
|
Additional arguments for the event loop. |
required |
Returns:
Type | Description |
---|---|
Tuple[StopReason, Message, EventLoopMetrics, Any]
|
The results from the event loop call if successful. |
Raises:
Type | Description |
---|---|
ContextWindowOverflowException
|
If messages cannot be truncated. |
Source code in strands/event_loop/error_handler.py
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 |
|
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
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 |
|
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 |
|
find_last_message_with_tool_results(messages)
¶
Find the index of the last message containing tool results.
This is useful for identifying messages that might need to be truncated to reduce context size.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
messages
|
Messages
|
The conversation message history. |
required |
Returns:
Type | Description |
---|---|
Optional[int]
|
Index of the last message with tool results, or None if no such message exists. |
Source code in strands/event_loop/message_processor.py
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 |
|
truncate_tool_results(messages, msg_idx)
¶
Truncate tool results in a message to reduce context size.
When a message contains tool results that are too large for the model's context window, this function replaces the content of those tool results with a simple error message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
messages
|
Messages
|
The conversation message history. |
required |
msg_idx
|
int
|
Index of the message containing tool results to truncate. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if any changes were made to the message, False otherwise. |
Source code in strands/event_loop/message_processor.py
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 |
|
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
241 242 243 244 245 246 247 248 249 250 251 252 253 |
|
handle_content_block_delta(event, state, callback_handler, **kwargs)
¶
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 |
callback_handler
|
Any
|
Callback for processing events as they happen. |
required |
**kwargs
|
Any
|
Additional keyword arguments to pass to the callback handler. |
{}
|
Returns:
Type | Description |
---|---|
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 155 156 |
|
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
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 |
|
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
214 215 216 217 218 219 220 221 222 223 |
|
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
226 227 228 229 230 231 232 233 234 235 236 237 238 |
|
process_stream(chunks, callback_handler, messages, **kwargs)
¶
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 |
callback_handler
|
Any
|
Callback for processing events as they happen. |
required |
messages
|
Messages
|
The agents messages. |
required |
**kwargs
|
Any
|
Additional keyword arguments that will be passed to the callback handler. And also returned in the request_state. |
{}
|
Returns:
Type | Description |
---|---|
Tuple[StopReason, Message, Usage, Metrics, Any]
|
The reason for stopping, the constructed message, the usage metrics, and the updated request state. |
Source code in strands/event_loop/streaming.py
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 |
|
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, callback_handler, **kwargs)
¶
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 |
callback_handler
|
Any
|
Callback for processing events as they happen. |
required |
**kwargs
|
Any
|
Additional keyword arguments that will be passed to the callback handler. And also returned in the request_state. |
{}
|
Returns:
Type | Description |
---|---|
Tuple[StopReason, Message, Usage, Metrics, Any]
|
The reason for stopping, the final message, the usage metrics, and updated request state. |
Source code in strands/event_loop/streaming.py
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 |
|