strands.telemetry.metrics
Utilities for collecting and reporting performance metrics in the SDK.
class Trace()Defined in: src/strands/telemetry/metrics.py:22
A trace representing a single operation or step in the execution flow.
__init__
Section titled “__init__”def __init__(name: str, parent_id: str | None = None, start_time: float | None = None, raw_name: str | None = None, metadata: dict[str, Any] | None = None, message: Message | None = None) -> NoneDefined in: src/strands/telemetry/metrics.py:25
Initialize a new trace.
Arguments:
name- Human-readable name of the operation being traced.parent_id- ID of the parent trace, if this is a child operation.start_time- Timestamp when the trace started. If not provided, the current time will be used.raw_name- System level name.metadata- Additional contextual information about the trace.message- Message associated with the trace.
def end(end_time: float | None = None) -> NoneDefined in: src/strands/telemetry/metrics.py:55
Mark the trace as complete with the given or current timestamp.
Arguments:
end_time- Timestamp to use as the end time. If not provided, the current time will be used.
add_child
Section titled “add_child”def add_child(child: "Trace") -> NoneDefined in: src/strands/telemetry/metrics.py:64
Add a child trace to this trace.
Arguments:
child- The child trace to add.
duration
Section titled “duration”def duration() -> float | NoneDefined in: src/strands/telemetry/metrics.py:72
Calculate the duration of this trace.
Returns:
The duration in seconds, or None if the trace hasn’t ended yet.
add_message
Section titled “add_message”def add_message(message: Message) -> NoneDefined in: src/strands/telemetry/metrics.py:80
Add a message to the trace.
Arguments:
message- The message to add.
to_dict
Section titled “to_dict”def to_dict() -> dict[str, Any]Defined in: src/strands/telemetry/metrics.py:88
Convert the trace to a dictionary representation.
Returns:
A dictionary containing all trace information, suitable for serialization.
ToolMetrics
Section titled “ToolMetrics”@dataclassclass ToolMetrics()Defined in: src/strands/telemetry/metrics.py:109
Metrics for a specific tool’s usage.
Attributes:
tool- The tool being tracked.call_count- Number of times the tool has been called.success_count- Number of successful tool calls.error_count- Number of failed tool calls.total_time- Total execution time across all calls in seconds.
add_call
Section titled “add_call”def add_call(tool: ToolUse, duration: float, success: bool, metrics_client: "MetricsClient", attributes: dict[str, Any] | None = None) -> NoneDefined in: src/strands/telemetry/metrics.py:126
Record a new tool call with its outcome.
Arguments:
tool- The tool that was called.duration- How long the call took in seconds.success- Whether the call was successful.metrics_client- The metrics client for recording the metrics.attributes- attributes of the metrics.
EventLoopCycleMetric
Section titled “EventLoopCycleMetric”@dataclassclass EventLoopCycleMetric()Defined in: src/strands/telemetry/metrics.py:157
Aggregated metrics for a single event loop cycle.
Attributes:
event_loop_cycle_id- Current eventLoop cycle id.usage- Total token usage for the entire cycle (succeeded model invocation, excluding tool invocations).
AgentInvocation
Section titled “AgentInvocation”@dataclassclass AgentInvocation()Defined in: src/strands/telemetry/metrics.py:170
Metrics for a single agent invocation.
AgentInvocation contains all the event loop cycles and accumulated token usage for that invocation.
Attributes:
cycles- List of event loop cycles that occurred during this invocation.usage- Accumulated token usage for this invocation across all cycles.
EventLoopMetrics
Section titled “EventLoopMetrics”@dataclassclass EventLoopMetrics()Defined in: src/strands/telemetry/metrics.py:185
Aggregated metrics for an event loop’s execution.
Attributes:
cycle_count- Number of event loop cycles executed.tool_metrics- Metrics for each tool used, keyed by tool name.cycle_durations- List of durations for each cycle in seconds.agent_invocations- Agent invocation metrics containing cycles and usage data.traces- List of execution traces.accumulated_usage- Accumulated token usage across all model invocations (across all requests).accumulated_metrics- Accumulated performance metrics across all model invocations.
latest_context_size
Section titled “latest_context_size”@propertydef latest_context_size() -> int | NoneDefined in: src/strands/telemetry/metrics.py:207
Most recent context size from the last LLM call.
This represents the current context size as reported by the model.
Returns:
The input token count from the most recent cycle, or None if no data is available.
projected_context_size
Section titled “projected_context_size”@propertydef projected_context_size() -> int | NoneDefined in: src/strands/telemetry/metrics.py:220
Projected context size for the next model call.
Computed as inputTokens + outputTokens from the most recent cycle’s usage, representing the approximate input token count for the next model call (prior input + generated output that is now part of the conversation).
Returns:
The projected token count, or None if no data is available.
latest_agent_invocation
Section titled “latest_agent_invocation”@propertydef latest_agent_invocation() -> AgentInvocation | NoneDefined in: src/strands/telemetry/metrics.py:244
Get the most recent agent invocation.
Returns:
The most recent AgentInvocation, or None if no invocations exist.
start_cycle
Section titled “start_cycle”def start_cycle(attributes: dict[str, Any]) -> tuple[float, Trace]Defined in: src/strands/telemetry/metrics.py:252
Start a new event loop cycle and create a trace for it.
Arguments:
attributes- attributes of the metrics, including event_loop_cycle_id.
Returns:
A tuple containing the start time and the cycle trace object.
end_cycle
Section titled “end_cycle”def end_cycle(start_time: float, cycle_trace: Trace, attributes: dict[str, Any] | None = None) -> NoneDefined in: src/strands/telemetry/metrics.py:280
End the current event loop cycle and record its duration.
Arguments:
start_time- The timestamp when the cycle started.cycle_trace- The trace object for this cycle.attributes- attributes of the metrics.
add_tool_usage
Section titled “add_tool_usage”def add_tool_usage(tool: ToolUse, duration: float, tool_trace: Trace, success: bool, message: Message) -> NoneDefined in: src/strands/telemetry/metrics.py:295
Record metrics for a tool invocation.
Arguments:
tool- The tool that was used.duration- How long the tool call took in seconds.tool_trace- The trace object for this tool call.success- Whether the tool call was successful.message- The message associated with the tool call.
update_usage
Section titled “update_usage”def update_usage(usage: Usage) -> NoneDefined in: src/strands/telemetry/metrics.py:353
Update the accumulated token usage with new usage data.
Arguments:
usage- The usage data to add to the accumulated totals.
reset_usage_metrics
Section titled “reset_usage_metrics”def reset_usage_metrics() -> NoneDefined in: src/strands/telemetry/metrics.py:376
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.
update_metrics
Section titled “update_metrics”def update_metrics(metrics: Metrics) -> NoneDefined in: src/strands/telemetry/metrics.py:384
Update the accumulated performance metrics with new metrics data.
Arguments:
metrics- The metrics data to add to the accumulated totals.
get_summary
Section titled “get_summary”def get_summary() -> dict[str, Any]Defined in: src/strands/telemetry/metrics.py:395
Generate a comprehensive summary of all collected metrics.
Returns:
A dictionary containing summarized metrics data. This includes cycle statistics, tool usage, traces, and accumulated usage information.
metrics_to_string
Section titled “metrics_to_string”def metrics_to_string(event_loop_metrics: EventLoopMetrics, allowed_names: set[str] | None = None) -> strDefined in: src/strands/telemetry/metrics.py:534
Convert event loop metrics to a human-readable string representation.
Arguments:
event_loop_metrics- The metrics to format.allowed_names- Set of names that are allowed to be displayed unmodified.
Returns:
A formatted string representation of the metrics.
MetricsClient
Section titled “MetricsClient”class MetricsClient()Defined in: src/strands/telemetry/metrics.py:547
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.
This class uses a thread-safe double-checked locking pattern to ensure safe concurrent initialization across multiple threads.
__new__
Section titled “__new__”def __new__(cls) -> "MetricsClient"Defined in: src/strands/telemetry/metrics.py:575
Create or return the singleton instance of MetricsClient.
Uses double-checked locking to ensure thread safety without acquiring the lock on every access after initialization.
Returns:
The single MetricsClient instance.
__init__
Section titled “__init__”def __init__() -> NoneDefined in: src/strands/telemetry/metrics.py:590
Initialize the MetricsClient.
This method only runs once due to the singleton pattern. Sets up the OpenTelemetry meter and creates metric instruments. Uses a lock to prevent concurrent initialization races.
create_instruments
Section titled “create_instruments”def create_instruments() -> NoneDefined in: src/strands/telemetry/metrics.py:610
Create and initialize all OpenTelemetry metric instruments.