strands.telemetry
¶
Telemetry module.
This module provides metrics and tracing functionality.
strands.telemetry.config
¶
OpenTelemetry configuration and setup utilities for Strands agents.
This module provides centralized configuration and initialization functionality for OpenTelemetry components and other telemetry infrastructure shared across Strands applications.
StrandsTelemetry
¶
OpenTelemetry configuration and setup for Strands applications.
Automatically initializes a tracer provider with text map propagators. Trace exporters (console, OTLP) can be set up individually using dedicated methods that support method chaining for convenient configuration.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tracer_provider
|
TracerProvider | None
|
Optional pre-configured SDKTracerProvider. If None, a new one will be created and set as the global tracer provider. |
None
|
Environment Variables
Environment variables are handled by the underlying OpenTelemetry SDK: - OTEL_EXPORTER_OTLP_ENDPOINT: OTLP endpoint URL - OTEL_EXPORTER_OTLP_HEADERS: Headers for OTLP requests
Examples:
Quick setup with method chaining:
Using a custom tracer provider:
Step-by-step configuration:
>>> telemetry = StrandsTelemetry()
>>> telemetry.setup_console_exporter()
>>> telemetry.setup_otlp_exporter()
To setup global meter provider
>>> telemetry.setup_meter(enable_console_exporter=True, enable_otlp_exporter=True) # default are False
Note
- The tracer provider is automatically initialized upon instantiation
- When no tracer_provider is provided, the instance sets itself as the global provider
- Exporters must be explicitly configured using the setup methods
- Failed exporter configurations are logged but do not raise exceptions
- All setup methods return self to enable method chaining
Source code in strands/telemetry/config.py
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 |
|
__init__(tracer_provider=None)
¶
Initialize the StrandsTelemetry instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tracer_provider
|
TracerProvider | None
|
Optional pre-configured tracer provider. If None, a new one will be created and set as global. |
None
|
The instance is ready to use immediately after initialization, though trace exporters must be configured separately using the setup methods.
Source code in strands/telemetry/config.py
setup_console_exporter(**kwargs)
¶
Set up console exporter for the tracer provider.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**kwargs
|
Any
|
Optional keyword arguments passed directly to OpenTelemetry's ConsoleSpanExporter initializer. |
{}
|
Returns:
Name | Type | Description |
---|---|---|
self |
StrandsTelemetry
|
Enables method chaining. |
This method configures a SimpleSpanProcessor with a ConsoleSpanExporter, allowing trace data to be output to the console. Any additional keyword arguments provided will be forwarded to the ConsoleSpanExporter.
Source code in strands/telemetry/config.py
setup_meter(enable_console_exporter=False, enable_otlp_exporter=False)
¶
Initialize the OpenTelemetry Meter.
Source code in strands/telemetry/config.py
setup_otlp_exporter(**kwargs)
¶
Set up OTLP exporter for the tracer provider.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**kwargs
|
Any
|
Optional keyword arguments passed directly to OpenTelemetry's OTLPSpanExporter initializer. |
{}
|
Returns:
Name | Type | Description |
---|---|---|
self |
StrandsTelemetry
|
Enables method chaining. |
This method configures a BatchSpanProcessor with an OTLPSpanExporter, allowing trace data to be exported to an OTLP endpoint. Any additional keyword arguments provided will be forwarded to the OTLPSpanExporter.
Source code in strands/telemetry/config.py
get_otel_resource()
¶
Create a standard OpenTelemetry resource with service information.
Returns:
Type | Description |
---|---|
Resource
|
Resource object with standard service information. |
Source code in strands/telemetry/config.py
strands.telemetry.metrics
¶
Utilities for collecting and reporting performance metrics in the SDK.
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. |
traces |
List[Trace]
|
List of execution traces. |
accumulated_usage |
Usage
|
Accumulated token usage across all model invocations. |
accumulated_metrics |
Metrics
|
Accumulated performance metrics across all model invocations. |
Source code in strands/telemetry/metrics.py
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 |
|
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
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
|
Optional[Dict[str, Any]]
|
attributes of the metrics. |
None
|
Source code in strands/telemetry/metrics.py
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
start_cycle(attributes=None)
¶
Start a new event loop cycle and create a trace for it.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
attributes
|
Optional[Dict[str, Any]]
|
attributes of the metrics. |
None
|
Returns:
Type | Description |
---|---|
Tuple[float, Trace]
|
A tuple containing the start time and the cycle trace object. |
Source code in strands/telemetry/metrics.py
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
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
MetricsClient
¶
Singleton client for managing OpenTelemetry metrics instruments.
The actual metrics export destination (console, OTLP endpoint, etc.) is configured through OpenTelemetry SDK configuration by users, not by this client.
Source code in strands/telemetry/metrics.py
__init__()
¶
Initialize the MetricsClient.
This method only runs once due to the singleton pattern. Sets up the OpenTelemetry meter and creates metric instruments.
Source code in strands/telemetry/metrics.py
__new__()
¶
Create or return the singleton instance of MetricsClient.
Returns:
Type | Description |
---|---|
MetricsClient
|
The single MetricsClient instance. |
Source code in strands/telemetry/metrics.py
create_instruments()
¶
Create and initialize all OpenTelemetry metric instruments.
Source code in strands/telemetry/metrics.py
ToolMetrics
dataclass
¶
Metrics for a specific tool's usage.
Attributes:
Name | Type | Description |
---|---|---|
tool |
ToolUse
|
The tool being tracked. |
call_count |
int
|
Number of times the tool has been called. |
success_count |
int
|
Number of successful tool calls. |
error_count |
int
|
Number of failed tool calls. |
total_time |
float
|
Total execution time across all calls in seconds. |
Source code in strands/telemetry/metrics.py
add_call(tool, duration, success, metrics_client, attributes=None)
¶
Record a new tool call with its outcome.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tool
|
ToolUse
|
The tool that was called. |
required |
duration
|
float
|
How long the call took in seconds. |
required |
success
|
bool
|
Whether the call was successful. |
required |
metrics_client
|
MetricsClient
|
The metrics client for recording the metrics. |
required |
attributes
|
Optional[Dict[str, Any]]
|
attributes of the metrics. |
None
|
Source code in strands/telemetry/metrics.py
Trace
¶
A trace representing a single operation or step in the execution flow.
Source code in strands/telemetry/metrics.py
__init__(name, parent_id=None, start_time=None, raw_name=None, metadata=None, message=None)
¶
Initialize a new trace.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Human-readable name of the operation being traced. |
required |
parent_id
|
Optional[str]
|
ID of the parent trace, if this is a child operation. |
None
|
start_time
|
Optional[float]
|
Timestamp when the trace started. If not provided, the current time will be used. |
None
|
raw_name
|
Optional[str]
|
System level name. |
None
|
metadata
|
Optional[Dict[str, Any]]
|
Additional contextual information about the trace. |
None
|
message
|
Optional[Message]
|
Message associated with the trace. |
None
|
Source code in strands/telemetry/metrics.py
add_child(child)
¶
Add a child trace to this trace.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
child
|
Trace
|
The child trace to add. |
required |
add_message(message)
¶
Add a message to the trace.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
Message
|
The message to add. |
required |
duration()
¶
Calculate the duration of this trace.
Returns:
Type | Description |
---|---|
Optional[float]
|
The duration in seconds, or None if the trace hasn't ended yet. |
end(end_time=None)
¶
Mark the trace as complete with the given or current timestamp.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
end_time
|
Optional[float]
|
Timestamp to use as the end time. If not provided, the current time will be used. |
None
|
Source code in strands/telemetry/metrics.py
to_dict()
¶
Convert the trace to a dictionary representation.
Returns:
Type | Description |
---|---|
Dict[str, Any]
|
A dictionary containing all trace information, suitable for serialization. |
Source code in strands/telemetry/metrics.py
metrics_to_string(event_loop_metrics, allowed_names=None)
¶
Convert event loop metrics to a human-readable string representation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event_loop_metrics
|
EventLoopMetrics
|
The metrics to format. |
required |
allowed_names
|
Optional[Set[str]]
|
Set of names that are allowed to be displayed unmodified. |
None
|
Returns:
Type | Description |
---|---|
str
|
A formatted string representation of the metrics. |
Source code in strands/telemetry/metrics.py
strands.telemetry.metrics_constants
¶
Metrics that are emitted in Strands-Agents.
strands.telemetry.tracer
¶
OpenTelemetry integration.
This module provides tracing capabilities using OpenTelemetry, enabling trace data to be sent to OTLP endpoints.
JSONEncoder
¶
Bases: JSONEncoder
Custom JSON encoder that handles non-serializable types.
Source code in strands/telemetry/tracer.py
encode(obj)
¶
Recursively encode objects, preserving structure and only replacing unserializable values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
obj
|
Any
|
The object to encode |
required |
Returns:
Type | Description |
---|---|
str
|
JSON string representation of the object |
Source code in strands/telemetry/tracer.py
Tracer
¶
Handles OpenTelemetry tracing.
This class provides a simple interface for creating and managing traces, with support for sending to OTLP endpoints.
When the OTEL_EXPORTER_OTLP_ENDPOINT environment variable is set, traces are sent to the OTLP endpoint.
Source code in strands/telemetry/tracer.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 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 |
|
__init__()
¶
Initialize the tracer.
Source code in strands/telemetry/tracer.py
end_agent_span(span, response=None, error=None)
¶
End an agent span with results and metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
span
|
Span
|
The span to end. |
required |
response
|
Optional[AgentResult]
|
The response from the agent. |
None
|
error
|
Optional[Exception]
|
Any error that occurred. |
None
|
Source code in strands/telemetry/tracer.py
end_event_loop_cycle_span(span, message, tool_result_message=None, error=None)
¶
End an event loop cycle span with results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
span
|
Span
|
The span to end. |
required |
message
|
Message
|
The message response from this cycle. |
required |
tool_result_message
|
Optional[Message]
|
Optional tool result message if a tool was called. |
None
|
error
|
Optional[Exception]
|
Optional exception if the cycle failed. |
None
|
Source code in strands/telemetry/tracer.py
end_model_invoke_span(span, message, usage, stop_reason, error=None)
¶
End a model invocation span with results and metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
span
|
Span
|
The span to end. |
required |
message
|
Message
|
The message response from the model. |
required |
usage
|
Usage
|
Token usage information from the model call. |
required |
stop_reason
|
StopReason
|
The reason the model stopped generating. |
required |
error
|
Optional[Exception]
|
Optional exception if the model call failed. |
None
|
Source code in strands/telemetry/tracer.py
end_span_with_error(span, error_message, exception=None)
¶
End a span with error status.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
span
|
Span
|
The span to end. |
required |
error_message
|
str
|
Error message to set in the span status. |
required |
exception
|
Optional[Exception]
|
Optional exception to record in the span. |
None
|
Source code in strands/telemetry/tracer.py
end_swarm_span(span, result=None)
¶
End a swarm span with results.
end_tool_call_span(span, tool_result, error=None)
¶
End a tool call span with results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
span
|
Span
|
The span to end. |
required |
tool_result
|
Optional[ToolResult]
|
The result from the tool execution. |
required |
error
|
Optional[Exception]
|
Optional exception if the tool call failed. |
None
|
Source code in strands/telemetry/tracer.py
start_agent_span(message, agent_name, model_id=None, tools=None, custom_trace_attributes=None, **kwargs)
¶
Start a new span for an agent invocation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
Message
|
The user message being sent to the agent. |
required |
agent_name
|
str
|
Name of the agent. |
required |
model_id
|
Optional[str]
|
Optional model identifier. |
None
|
tools
|
Optional[list]
|
Optional list of tools being used. |
None
|
custom_trace_attributes
|
Optional[Mapping[str, AttributeValue]]
|
Optional mapping of custom trace attributes to include in the span. |
None
|
**kwargs
|
Any
|
Additional attributes to add to the span. |
{}
|
Returns:
Type | Description |
---|---|
Optional[Span]
|
The created span, or None if tracing is not enabled. |
Source code in strands/telemetry/tracer.py
start_event_loop_cycle_span(invocation_state, messages, parent_span=None, **kwargs)
¶
Start a new span for an event loop cycle.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
invocation_state
|
Any
|
Arguments for the event loop cycle. |
required |
parent_span
|
Optional[Span]
|
Optional parent span to link this span to. |
None
|
messages
|
Messages
|
Messages being processed in this cycle. |
required |
**kwargs
|
Any
|
Additional attributes to add to the span. |
{}
|
Returns:
Type | Description |
---|---|
Optional[Span]
|
The created span, or None if tracing is not enabled. |
Source code in strands/telemetry/tracer.py
start_model_invoke_span(messages, parent_span=None, model_id=None, **kwargs)
¶
Start a new span for a model invocation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
messages
|
Messages
|
Messages being sent to the model. |
required |
parent_span
|
Optional[Span]
|
Optional parent span to link this span to. |
None
|
model_id
|
Optional[str]
|
Optional identifier for the model being invoked. |
None
|
**kwargs
|
Any
|
Additional attributes to add to the span. |
{}
|
Returns:
Type | Description |
---|---|
Optional[Span]
|
The created span, or None if tracing is not enabled. |
Source code in strands/telemetry/tracer.py
start_multiagent_span(task, instance)
¶
Start a new span for swarm invocation.
Source code in strands/telemetry/tracer.py
start_tool_call_span(tool, parent_span=None, **kwargs)
¶
Start a new span for a tool call.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tool
|
ToolUse
|
The tool being used. |
required |
parent_span
|
Optional[Span]
|
Optional parent span to link this span to. |
None
|
**kwargs
|
Any
|
Additional attributes to add to the span. |
{}
|
Returns:
Type | Description |
---|---|
Optional[Span]
|
The created span, or None if tracing is not enabled. |
Source code in strands/telemetry/tracer.py
get_tracer()
¶
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 |