
Day 13 -Trace Your AI Agent with OpenTelemetry and Amazon CloudWatch
Learn how to trace AI agent execution using Strands Agents, OpenTelemetry, Amazon Bedrock, and Amazon CloudWatch.
Series: 30 Days of AI Engineering on AWS (17 articles)
- …
- 14Day 13 -Trace Your AI Agent with OpenTelemetry and Amazon CloudWatch This article
In Day 12, we built an automated evaluation pipeline.
We created a golden dataset, invoked our AWS Lambda agent, validated responses, and generated pass/fail reports.
That helped us answer an important question:
Did the application produce the expected result?
But there is another question.
How did the agent produce that result?
Imagine asking an AI assistant:
Calculate 18% of 1250.
The agent responds:
-
The answer is correct.
Our Day 12 evaluation would probably mark that request as successful.
But what if the agent was explicitly instructed to use a calculator tool?
Did it actually execute the tool?
Or did the foundation model generate the answer directly?
Now imagine a more complicated application. An AI agent retrieves documents, calls external APIs, processes information, and produces a final response.
If that response is incorrect, where did the problem occur?
Was the wrong tool selected? Did an API return an unexpected result? Did a model invocation fail? Or did the agent spend too long repeating an unnecessary operation?
Simply reading the final response won't answer these questions.
We need visibility into the agent's execution.
That is where OpenTelemetry and AI agent tracing become useful.
1. What is AI agent observability?
Observability is the ability to understand a system's internal behavior through the information it produces.
In traditional software, engineers commonly use three types of telemetry.
Telemetry | What it helps us understand |
|---|---|
Logs | What events occurred |
Metrics | How the application is performing over time |
Traces | How an individual request moved through the system |
For AI agents, tracing is particularly valuable because a single user request can trigger multiple operations.
An agent might:
- Receive a question.
- Invoke a foundation model.
- Select a tool.
- Execute that tool.
- Return the tool result to the model.
- Invoke the model again.
- Generate the final response.
A trace helps us follow this sequence.
Instead of only knowing that the answer took five seconds, we can investigate which operations contributed to that time.
Strands Agents includes native OpenTelemetry tracing capabilities for agent execution, model interactions, tool calls, and other internal operations.
2. Understand traces and spans
Before writing code, let's understand two essential concepts.
Trace
A trace represents the execution path of a request.
Span
A span represents an individual operation within that trace.
For example, our calculator agent might produce a trace similar to this:
Trace: User Request│├── Agent Execution│ ││ ├── Model Invocation 1│ │ └── Select calculate_percentage│ ││ ├── Tool Execution│ │ └── calculate_percentage│ ││ └── Model Invocation 2│ └── Generate Final Answer│└── Request CompleteEach span can contain metadata such as:
- Operation name.
- Start time.
- End time.
- Duration.
- Execution status.
- Tool name.
- Model identifier.
- Token usage, where reported.
The exact spans and attributes depend on the framework version, instrumentation, and model provider.
A single trace can contain several related spans.
OpenTelemetry connects them using trace IDs, span IDs, and parent relationships.
This makes it possible to reconstruct the execution path rather than viewing a collection of unrelated log messages.
3. Our Day 13 architecture
Today, we'll extend the calculator agent from Day 8.
We will start locally to understand the tracing data before exploring how to export it to Amazon CloudWatch.
User Prompt | v Strands Agent | v Amazon Bedrock (Nova Lite) | Agent Decision | +------+------+ | | v v Tool Call Direct Answer | | v | Python Calculator | | | +------+------+ | v Final Answer
OpenTelemetry | Capture Spans | +------+------+ | | v v Model Spans Tool Spans | | +------+------+ | v traces.jsonl | v Trace Analyzer | v Execution FindingsOur goal is to capture evidence of two different behaviors:
Test A: The agent should call the calculator tool.
Test B: The agent should answer a general AWS question without unnecessarily calling the calculator.
Later, we'll examine how the same tracing approach can be used in AWS Lambda with CloudWatch.
4. Prerequisites
You'll need:
- Python 3.12.
- An AWS account with Amazon Bedrock model access.
- Configured AWS credentials.
- Basic Python knowledge.
- Familiarity with the Day 8 Strands agent.
We'll use the same Region:
ap-south-1And the APAC inference profile:
apac.amazon.nova-lite-v1:0Remember that the APAC profile supports cross-Region inference. Invoking it from Mumbai does not guarantee that model processing remains exclusively within Mumbai.
We will use Strands Agents SDK version
1.65.0 , published on November 13, 2026.For this version, Strands provides an
otel optional dependency that includes the additional packages required for OpenTelemetry exporting.5. Create the project
Open PowerShell:
mkdir aws-agent-observabilitycd aws-agent-observabilityCreate the Python environment:
py -3.12 -m venv .venv
.venv\Scripts\Activate.ps1Install the SDK with the OpenTelemetry extra:
python -m pip install --upgrade pip
pip install "strands-agents[otel]==1.65.0"Configure the AWS Region:
$env:AWS_REGION = "ap-south-1"
$env:BEDROCK_MODEL_ID = "apac.amazon.nova-lite-v1:0"Verify credentials:
aws sts get-caller-identityYour principal still needs the Amazon Bedrock permissions required to invoke this inference profile and its destination foundation-model resources.
For local testing, we won't configure a remote OpenTelemetry collector.
We'll export spans into a local file so that we can inspect them directly.
Important: Tracing can capture prompts, model responses, system instructions, and tool arguments. Use only synthetic test data in this exercise. Do not publish the generated trace file.
6. Build the instrumented Strands agent
Create:
agent.pyOur application will have three important elements:
- A custom Python calculator tool.
- An Amazon Bedrock-powered Strands agent.
- An OpenTelemetry exporter that writes trace spans into a file.
Here's the complete implementation.
"""Day 13: Observe a Strands AI agent with OpenTelemetry."""
import osfrom decimal import Decimal, InvalidOperationfrom pathlib import Path
from opentelemetry import trace
from strands import Agent, toolfrom strands.models import BedrockModelfrom strands.telemetry import StrandsTelemetry
@tooldef calculate_percentage( amount: str, percentage: str) -> str: """ Calculate a percentage of a finite number exactly.
Args: amount: A decimal number represented as text. percentage: A percentage represented as text. """
try: base = Decimal(amount) rate = Decimal(percentage)
except (InvalidOperation, ValueError, TypeError): return "Invalid numeric input."
if not ( base.is_finite() and rate.is_finite() ): return "Only finite numbers are accepted."
value = base * rate / Decimal("100")
return ( f"{percentage}% of {amount} = {value:f}" )
def main():
model = BedrockModel( model_id=os.getenv( "BEDROCK_MODEL_ID", "apac.amazon.nova-lite-v1:0" ),
region_name=os.getenv( "AWS_REGION", "ap-south-1" ),
temperature=0.1, max_tokens=400 )
# Only use synthetic prompts. # Traces can contain model and tool content.
with Path("traces.jsonl").open( "w", encoding="utf-8" ) as output:
StrandsTelemetry().setup_console_exporter( out=output,
formatter=lambda span: ( span.to_json(indent=None) + "\n" ) )
tracer = trace.get_tracer( "day13.observability" )
test_cases = [ ( "calculator", "Use calculate_percentage to compute " "18 percent of 1250. State the result." ),
( "general", "In one sentence, explain what " "AWS Lambda does." ) ]
for scenario, prompt in test_cases:
agent = Agent( model=model,
tools=[calculate_percentage],
system_prompt=( "You are an AWS learning assistant. " "Always call calculate_percentage " "for percentage arithmetic. " "For unrelated questions, " "answer without calling the tool." ),
callback_handler=None,
name="day13-learning-agent" )
with tracer.start_as_current_span( "day13.request" ) as parent:
parent.set_attribute( "demo.scenario", scenario )
result = agent(prompt)
trace_id = ( f"{parent.get_span_context().trace_id:032x}" )
print( f"\n[{scenario}] Trace ID: {trace_id}" )
print( f"Answer: {str(result)}" )
provider = trace.get_tracer_provider()
if hasattr(provider, "force_flush"): provider.force_flush( timeout_millis=10000 )
print("\nSaved traces to traces.jsonl")
if __name__ == "__main__": main()Understand the instrumentation
The important addition is:
from strands.telemetry import StrandsTelemetryStrands provides the
StrandsTelemetry utility for configuring OpenTelemetry exporters.We're using:
StrandsTelemetry().setup_console_exporter( out=output, formatter=lambda span: span.to_json(indent=None) + "\n")This creates a trace exporter and writes each exported span as one JSON object per line.
We use
indent=None deliberately so that the output is valid JSON Lines format instead of pretty-printed, multiline JSON.Our file is:
traces.jsonlWe also create an application-level parent span:
with tracer.start_as_current_span("day13.request") as parent:This provides a trace context for the entire request.
Inside it, we invoke the Strands agent.
The framework can then emit its own child spans for the model and tool operations.
We add a harmless identifier:
parent.set_attribute( "demo.scenario", scenario)This allows us to distinguish the calculator test from the general-knowledge test.
Finally, we flush the configured tracer provider before closing the file.
The code follows the documented Strands
StrandsTelemetry , console exporter, and custom-span APIs.7. Run the application
Execute:
python agent.pyThe script sends two requests to Amazon Bedrock.
First:
Use calculate_percentage to compute18 percent of 1250.Second:
In one sentence, explain what AWS Lambda does.You should receive generated responses and trace identifiers.
For the calculator request, the correct numerical result is:
225The application also creates:
traces.jsonlOpen the file in VS Code.
You should see a collection of JSON span records containing identifiers, timing information, status information, and available OpenTelemetry attributes.
A simplified example of the information represented by a tool span might look like:
{ "name": "execute_tool calculate_percentage", "attributes": { "gen_ai.tool.name": "calculate_percentage", "tool.status": "success" }}This is illustrative, not a complete serialized OpenTelemetry span.
Actual exported records contain additional metadata and can use different span names depending on the SDK's instrumentation.
8. Find the evidence that a tool actually executed
This is the most important part of today's exercise.
Strands documents the attribute:
gen_ai.tool.namefor identifying tool execution.
Search
traces.jsonl for:calculate_percentageYou may find it in several places, including a tool description, model output, or tool invocation record.
However, a string match alone is not conclusive.
To identify actual tool execution, look for a span with the attribute:
{ "gen_ai.tool.name": "calculate_percentage"}Then inspect its associated trace ID, execution status, and duration.
That provides stronger evidence than checking whether the final answer merely mentioned the calculator.
For a more reliable check, let's build a small trace analyzer.
9. Create the trace analyzer
Create:
inspect_traces.pyThis script reads the local span file, groups records by trace ID, and identifies observed tool calls.
It also measures the duration of recorded spans and checks whether the two test scenarios followed their expected paths.
"""Inspect exported OpenTelemetry traces."""
import jsonimport sys
from collections import defaultdictfrom datetime import datetimefrom pathlib import Path
def duration_ms(span):
start = span.get("start_time") end = span.get("end_time")
if not start or not end: return None
start_dt = datetime.fromisoformat( start.replace("Z", "+00:00") )
end_dt = datetime.fromisoformat( end.replace("Z", "+00:00") )
return round( (end_dt - start_dt).total_seconds() * 1000 )
def inspect(path="traces.jsonl"):
records = [ json.loads(line)
for line in Path(path).read_text( encoding="utf-8" ).splitlines()
if line.strip() ]
by_trace = defaultdict(list)
for span in records:
trace_id = ( span.get("context") or {} ).get("trace_id")
if trace_id: by_trace[trace_id].append(span)
results = {}
for trace_id, spans in by_trace.items():
root = next( ( s for s in spans if s.get("name") == "day13.request" ), None )
if not root: continue
scenario = ( root.get("attributes") or {} ).get("demo.scenario", "unknown")
tool_spans = [ s for s in spans
if ( s.get("attributes") or {} ).get("gen_ai.tool.name") ]
tools = [ ( s.get("attributes") or {} ).get("gen_ai.tool.name")
for s in tool_spans ]
errors = [ s.get("name", "unknown")
for s in spans
if ( s.get("status") or {} ).get("status_code") == "ERROR" ]
results[scenario] = { "trace_id": trace_id, "spans": len(spans), "tools": tools, "errors": errors }
print(f"\nScenario: {scenario}") print(f"Trace ID: {trace_id}")
print( f"Total spans: {len(spans)}; " f"request duration: {duration_ms(root)} ms" )
print( "Observed tool calls:", tools or "none" )
print( "Error spans:", errors or "none" )
print("Longest spans:")
ordered = sorted( spans,
key=lambda s: duration_ms(s) or 0,
reverse=True )[:4]
for s in ordered: print( f" {s.get('name', '?')}: " f"{duration_ms(s)} ms" )
if not results: print("No Day 13 traces found.") return 2
if ( "calculator" not in results or "general" not in results ): print("Missing a required test scenario.") return 2
if ( "calculate_percentage" not in results["calculator"]["tools"] ): print( "FAIL: Expected calculator tool span missing." ) return 1
if results["general"]["tools"]: print( "FAIL: General question triggered a tool call." ) return 1
if any( result["errors"] for result in results.values() ): print("FAIL: Error spans were recorded.") return 1
print( "\nPASS: Expected tool routing observed." )
return 0
if __name__ == "__main__":
raise SystemExit( inspect( sys.argv[1] if len(sys.argv) > 1 else "traces.jsonl" ) )Run the analyzer:
python inspect_traces.pyIt will report the recorded spans and tool calls for each scenario.
A successful run should show that:
- The calculator request produced a
calculate_percentagetool span.
- The general AWS question did not produce a calculator tool span.
- No recorded spans reported an OpenTelemetry error status.
The analyzer exits with a nonzero status when the expected tool behavior is not observed.
Important: A missing tool span is evidence that the exported trace does not show the tool invocation. It does not automatically prove the tool was never called. Incorrect instrumentation, exporter failures, or incomplete tracing can also create missing spans.
This distinction becomes important in production monitoring.
10. Use traces to investigate latency
Now we have another useful capability.
Every completed span can record a start time and end time.
We calculate its duration using:
(end_dt - start_dt).total_seconds() * 1000This produces milliseconds.
For example, an illustrative trace might contain:
Operation | Duration |
|---|---|
Complete request | 3,400 ms |
First model invocation | 1,400 ms |
Calculator execution | 4 ms |
Second model invocation | 1,700 ms |
These values are examples, not measured results from this project.
They help demonstrate something important.
If the calculator took only a few milliseconds but the model invocations took several seconds, optimizing the calculator would probably not produce a meaningful improvement in overall latency.
Instead, we would investigate model calls, prompt size, inference latency, and unnecessary reasoning cycles.
This is the purpose of tracing.
It helps us identify which operations deserve attention.
One important caution: Do not blindly add the durations of every span.
Spans can be nested or overlap in time. Summing them can double-count execution time.
Use the parent-child relationships and timeline to understand the critical path.
11. Understand token usage in traces
Strands also documents token-related attributes that may be captured when the model provider reports usage.
For example:
gen_ai.usage.input_tokensgen_ai.usage.output_tokensgen_ai.usage.total_tokensThese can help identify why an agent consumes more tokens than expected.
Consider a case where a single request triggers several model invocations.
Maybe the agent repeatedly calls a tool.
Maybe a specialist is receiving unnecessary context.
Maybe a system prompt contains information that could be retrieved only when required.
Tracing can help identify those patterns.
However, avoid summing token values across every span without understanding their meaning.
An agent-level span may already include aggregated token usage from child model invocations.
Adding the agent's total to the individual model-invocation totals could double-count usage.
For an accurate application-level accounting system, define which spans contain per-invocation values and which contain aggregates.
Also remember that token counts are not necessarily equal to billing amounts. Costs depend on model pricing, routing, input/output categories, caching, and other applicable charges.
12. Move observability to AWS Lambda
So far, we've used a local file exporter.
That is useful for development, but a deployed application needs centralized observability.
AWS supports exporting OpenTelemetry data to Amazon CloudWatch using the AWS Distro for OpenTelemetry (ADOT).
We can extend the Day 8 Lambda application without moving the agent to AgentCore Runtime.
A. Enable CloudWatch Transaction Search
Open the Amazon CloudWatch console.
In the Mumbai Region, navigate to:
CloudWatch → Settings → X-Ray traces → Transaction Search
Enable Transaction Search if it has not already been enabled in that account and Region.
This is a one-time regional setup.
AWS notes that newly enabled Transaction Search can take approximately ten minutes to make spans available for search.
This setup may have billing implications depending on the trace volume, indexing configuration, and applicable pricing.
B. Add the AWS OpenTelemetry Lambda layer
For Python functions in Mumbai, the current ADOT documentation lists:
arn:aws:lambda:ap-south-1:615299751070:layer:AWSOpenTelemetryDistroPython:30This layer comes from AWS's regional OpenTelemetry distribution, not from our Day 8 Strands Lambda layer.
In Lambda, open:
Function → Layers → Add a layer → Specify an ARN
Add the appropriate Python OpenTelemetry layer.
C. Enable the execution wrapper
Configure the environment variable:
AWS_LAMBDA_EXEC_WRAPPER=/opt/otel-instrumentThis activates the OpenTelemetry instrumentation provided by the Lambda layer.
For the dedicated agent-observability configuration, AWS also documents settings such as:
AGENT_OBSERVABILITY_ENABLED=trueOTEL_PYTHON_DISTRO=aws_distroOTEL_PYTHON_CONFIGURATOR=aws_configuratorOTEL_PYTHON_DISABLED_INSTRUMENTATIONS=noneOTEL_AWS_APPLICATION_SIGNALS_ENABLED=falseOTEL_TRACES_EXPORTER=otlpOTEL_EXPORTER_OTLP_PROTOCOL=http/protobufOTEL_LOGS_EXPORTER=noneOTEL_METRICS_EXPORTER=noneSetting
OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=none enables additional instrumentations, but can increase Lambda cold-start duration.A production deployment may use AWS Application Signals as well. If you deliberately disable it, that changes the additional observability features available.
D. Configure IAM permissions
The Lambda execution role requires permission to export trace data.
AWS's CloudWatch AI telemetry documentation specifies the managed policy:
AWSXrayWriteOnlyAccessThe broader ADOT Application Signals setup documents:
CloudWatchLambdaApplicationSignalsExecutionRolePolicyUse permissions appropriate to the tracing configuration you deploy.
Keep the existing Amazon Bedrock invocation permissions.
Also verify that the Lambda function has the required Strands SDK and OpenTelemetry dependencies.
Packaging consideration: The earlier Strands layer from Day 8 may contain a different SDK version. Do not assume it provides the same
strands-agents[otel]==1.65.0 dependencies used in today's local exercise. Build and test a compatible deployment package or layer for the version you choose.Finally, don't add a second
StrandsTelemetry() provider inside code running under the ADOT wrapper.The AWS distribution configures the global OpenTelemetry tracer provider. Strands can use that existing provider.
Creating another provider independently can cause missing or incorrectly exported traces.
13. Inspect traces in Amazon CloudWatch
Once the Lambda function is correctly instrumented and has received requests, open CloudWatch.
Navigate to Generative AI Observability or Transaction Search.
Depending on your configuration, you can investigate:
- Agent executions.
- Model calls.
- Tool invocations.
- Trace timelines.
- Latency.
- Errors.
- Token-usage metadata.
You can also investigate individual traces using their trace identifiers.
This is useful when a user reports:
The AI agent gave the wrong response.
Instead of guessing what happened, an engineer can inspect the request's recorded execution path.
For example:
User Request | vAgent Invocation | vModel Selects Tool | vTool Returns Error | vModel Generates Final AnswerThat trace would tell us that a tool error occurred during processing.
We could then investigate whether the agent handled the error correctly.
CloudWatch also provides model-invocation dashboards with information such as invocation counts, token usage, latency, and errors.
Keep in mind that Bedrock model monitoring and application-level Strands tracing are related but different layers of observability. Model metrics alone do not establish which agent tools executed.
14. Protect sensitive information in telemetry
This is one of the most important production considerations.
OpenTelemetry traces can contain more than timing information.
Depending on instrumentation settings, spans or events may include:
- User prompts.
- System instructions.
- Generated responses.
- Tool arguments.
- Tool results.
- Document content.
- Identifiers associated with users or sessions.
Strands explicitly documents that its telemetry can contain sensitive information and requires deliberate controls.
For this reason, do not use actual personal information or confidential documents in today's local trace file.
In production, apply a data-minimization strategy.
Use redaction or filtering before storing telemetry, restrict who can access traces, configure retention, and avoid capturing information that is unnecessary for monitoring.
Strands documents an OpenTelemetry semantic-convention redaction configuration, but do not assume one setting removes every sensitive field from every framework version or exporter.
AWS's ADOT instrumentation also supports controls for sensitive trace attributes.
Additionally, AWS's
AWS_GENAI_CONTENT_EXTRACTION_OPT_OUT=true setting keeps model and tool content on spans; it is not a privacy-protection switch. Do not enable it simply to reduce data exposure.For production, verify the actual exported payload rather than assuming that tracing is metadata-only.
Official references:
15. Tracing versus evaluation: why we need both
This connects directly to Day 12.
Evaluation helps answer:
Did the agent do the right thing?
Tracing helps answer:
What did the agent actually do?
Consider this example:
Situation | Evaluation result | What tracing reveals |
|---|---|---|
Correct calculation through tool | Pass | Calculator tool executed |
Correct calculation without required tool | May pass | No calculator tool invocation was observed |
Incorrect answer after a tool error | Fail | Tool execution reported an error |
Slow but accurate answer | Pass on correctness | Excessive model invocations or other latency |
Correct answer with unnecessary delegation | May pass | Unnecessary specialist/tool calls |
Together, evaluation and tracing give us a stronger picture of agent behavior.
However, neither one proves everything.
A trace cannot establish that a technical answer is factually correct.
An evaluation score does not necessarily tell us why an agent failed.
For production systems, the two approaches should complement each other.
This is also why trace-based evaluation is useful for multi-agent architectures.
Amazon Bedrock AgentCore Evaluations can analyze agent traces, provided the required telemetry and evaluation setup has been configured.
Today's OpenTelemetry work establishes the kind of execution visibility that makes such evaluations possible.
16. Production engineering considerations
Before applying this approach to a real workload, remember the following.
Instrument the whole execution path.
If an agent invokes Lambda, external APIs, databases, or other agents, a useful end-to-end trace requires appropriate instrumentation and propagation of trace context across those boundaries.
Do not assume traces are always complete.
Sampling, exporter failures, missing instrumentation, or unsupported operations can cause incomplete traces.
Our local trace analyzer should be treated as a development tool, not a complete production monitoring system.
Monitor telemetry overhead.
Instrumentation and exporting can add CPU, memory, network usage, and execution time.
The effect depends on trace volume and export configuration.
Control cardinality.
Use stable service names and operation names.
Avoid creating unique metric dimensions or operation names for every user prompt.
Do not turn observability into a data leak.
A system that captures every prompt, response, and tool result without data protection can create a larger privacy and security problem than the original application.
Do not confuse successful execution with correct behavior.
An agent can complete every tool call without error and still produce an inaccurate or harmful response.
This is why Day 12's evaluations remain necessary.
Your Day 13 challenge
Extend your Strands agent with OpenTelemetry tracing.
Complete these objectives:
- Capture a trace for a percentage calculation.
- Identify the actual
calculate_percentagetool span.
- Capture a trace for a general AWS question.
- Check that the unrelated request did not invoke the calculator.
- Compare the recorded request durations and inspect any error spans.
For the optional cloud challenge, configure ADOT tracing on a staging copy of the Day 8 Lambda function and examine the results in Amazon CloudWatch.
The goal is to move from simply observing final answers to understanding the operations that produced those answers.
What you learned today
Today, you explored AI agent observability using Strands Agents, OpenTelemetry, Amazon Bedrock, and Amazon CloudWatch.
You learned how to create traces, identify tool execution spans, inspect latency, correlate operations using trace IDs, and distinguish evaluation from execution tracing.
The most important takeaway:
A correct answer does not necessarily mean an AI agent followed the correct execution path.
When you're building tool-using or multi-agent applications, you need visibility into the decisions and operations that produce the result.
Day 12 helped us measure whether the answer met expectations.
Day 13 helps us understand what happened along the way.
30 Days. 30 Tasks. Real AI Building.
Series: 30 Days of AI Engineering on AWS (17 articles)
- …
- 14Day 13 -Trace Your AI Agent with OpenTelemetry and Amazon CloudWatch This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article