Lab: Instrumenting the Loop with Spans
Instrument an agent loop with the OpenTelemetry SDK and the GenAI semantic conventions: nested spans for the run, model calls and tool calls, token usage read from responses, opt-in content capture, and a redaction helper with a test that no secret reaches an exported span.
Contentsand lesson path
On this page
- OpenTelemetry GenAI Semantic Conventions in Practice
- Implementing Span Context Managers Across Loop Turns
- Lab: Run the Instrumented Loop and Read Its Spans
- Practice questions
- Apply it
- Review prompt
Lessons of Agent Tracing & Debugging
- Why Agents Need Traces, Not Just Logs Concept · 15 min
- Lab: Instrumenting the Loop with Spans Lab · 25 min
- Reading a Failed Trace Worked example · 20 min
- Building a Failure Taxonomy from 20 Runs Lab · 25 min
- Cost and Latency per Step Worked example · 15 min
- Check: Find the Faulty Step Knowledge check · 6 questions
What you will learn
- Instrument an agent with nested spans for runs, model calls and tool calls using the OpenTelemetry GenAI semantic conventions or an equivalent tracing SDK, with sensitive content redacted.
01. OpenTelemetry GenAI Semantic Conventions in Practice
Before shared conventions existed, each tracing tool named the same facts differently, such as prompt_tokens in one library and input_token_count in another, so every dashboard needed custom parsing for each framework.
The OpenTelemetry GenAI semantic conventions define shared span names and attributes. They are in Development status and now live in the separate semantic-conventions-genai repository, whose first release, v0.1.0, came out on 21 November 2026. Names can still change between releases, so note the release or commit you follow; this lab follows v0.1.0. Every GenAI span carries gen_ai.operation.name, and the span name is built from it. Three kinds of span matter for an agent loop:
- Agent invocation: span name
invoke_agent {gen_ai.agent.name}, for exampleinvoke_agent SupportTriageAgent, withgen_ai.operation.name = invoke_agentandgen_ai.agent.name. An agent that runs inside your own process gets span kind INTERNAL, and the current conventions no longer listgen_ai.provider.nameon that span: the model spans carry the provider. - Model call: span name
{gen_ai.operation.name} {gen_ai.request.model}, for examplechat gpt-6-luna, span kind CLIENT. Attributes includegen_ai.provider.name(for exampleopenaioranthropic; it replaced the deprecatedgen_ai.system),gen_ai.request.model,gen_ai.response.model,gen_ai.usage.input_tokens,gen_ai.usage.output_tokensandgen_ai.response.finish_reasons(such asstoportool_calls). - Tool execution: span name
execute_tool {gen_ai.tool.name}, span kind INTERNAL, withgen_ai.tool.name,gen_ai.tool.call.idand, on failure,error.typeplus an error span status. A span per loop turn is a useful custom addition but is not part of the conventions.
Many backends recognise these names, though some map them more fully than others. Instrumentation libraries can also lag behind: the Python OpenAI instrumentation (opentelemetry-instrumentation-openai-v2 2.4b0) follows conventions v1.30.0, which still used gen_ai.system, unless you set OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental. That variable is now the library's own switch: v0.1.0 of the conventions removed the transition guidance that defined it, so read your library's docs for what it emits. This lab writes attribute names as plain strings, because in opentelemetry-semantic-conventions 0.66b2 the gen_ai constants are marked deprecated (they moved to the new repository) and newer names are missing.
The conventions also define attributes that hold what was actually said: gen_ai.input.messages, gen_ai.output.messages and gen_ai.system_instructions on model spans, and gen_ai.tool.call.arguments and gen_ai.tool.call.result on tool spans. All of them are marked Opt-In, because prompts, replies and tool arguments often contain personal data, passwords or card numbers. The specification says instrumentations should not capture this content by default. The conventions name the switch OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT, default NO_CONTENT; some libraries still use an older name, such as OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT in the Python OpenAI instrumentation, so check the docs of yours. For production, the specification suggests storing content outside the trace, behind its own access control, and putting only a reference on the span.
Turning content off does not remove every risk. An error message such as no charges on card 4111 1111 1111 1111 ends up in the exception event and the span status, which are not content attributes. So the code in this lab does three things: it records content only when the setting asks for it, it passes everything it records, error text included, through a redact() helper, and it has a test that searches the exported spans for the secrets. A redaction rule without a test is a guess.
02. Implementing Span Context Managers Across Loop Turns
In Python, tracer.start_as_current_span(...) is a context manager. Any span opened inside its with block becomes a child: it gets the same trace ID and the outer span as its parent, through a context variable, so helper functions need no IDs passed in.
OpenTelemetry Baggage carries key-value pairs such as tenant_id in the same context and, with the baggage propagator, to downstream services. It is not copied onto spans automatically: copy it yourself or with a baggage span processor. Baggage travels in plain HTTP headers, so never put secrets or personal data in it.
During each turn, the loop opens two kinds of child span:
- Model spans: before calling the model, the loop opens a
chat {model}span of kind CLIENT. When the response arrives, it reads token usage from the response object, not from an estimate, sets the attributes and closes the span. - Tool spans: for each tool call, the loop opens an
execute_tool {tool}span. Span status is not an attribute. When a tool fails, callspan.record_exception(exc)andspan.set_status(Status(StatusCode.ERROR, description)), and seterror.type. An attribute namedstatus.codeis just another string that backends ignore. An exception that escapes astart_as_current_spanblock is recorded for you; this loop catches tool errors so the model can see them, so it records them itself.
Only when capture_content() returns true does a tool span also get gen_ai.tool.call.arguments and gen_ai.tool.call.result, both passed through redact(). record_exception stores the exception message and a stack trace whose last line repeats that message, so the code overrides both with redacted text. Since opentelemetry-sdk 1.45.0 an attribute value can be a dict, which is the structured value the conventions ask for. Older SDK versions reject it with an invalid-type warning. A json.dumps(redact(args)) string was the usual fallback there, but v0.1.0 requires the structured value on spans, so upgrade the SDK instead.
First the redaction helper. It masks the value under any key it knows is sensitive and scrubs every string with two patterns. The card pattern also masks other long digit runs, such as some order numbers; that is the safer mistake.
"""Mask secrets and personal data before they are written to a span."""
import re
SENSITIVE_KEYS = {"password", "token", "api_key", "secret", "card_number", "cvv"}
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
CARD = re.compile(r"\b\d(?:[ -]?\d){12,18}\b") # 13-19 digits, spaces allowed
def redact_text(text):
return CARD.sub("[CARD]", EMAIL.sub("[EMAIL]", text))
def redact(value):
"""Return a copy with sensitive keys masked and every string scrubbed."""
if isinstance(value, dict):
return {key: "[REDACTED]" if key.lower() in SENSITIVE_KEYS else redact(item)
for key, item in value.items()}
if isinstance(value, (list, tuple)):
return [redact(item) for item in value]
if isinstance(value, str):
return redact_text(value)
return valueNow the instrumented loop. It imports only the OpenTelemetry API; the lab configures the SDK. The model name comes from OPENAI_MODEL.
"""An agent loop instrumented with OpenTelemetry GenAI semantic-convention spans."""
import os
import traceback
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
from redact import redact, redact_text
tracer = trace.get_tracer("support-agent", "1.0.0")
PROVIDER, AGENT = "openai", "SupportTriageAgent"
MODEL = os.environ.get("OPENAI_MODEL", "gpt-6-luna")
CAPTURE_VAR = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT"
def capture_content():
"""Message and argument content is opt-in: off unless the variable asks for it."""
mode = os.environ.get(CAPTURE_VAR, "NO_CONTENT").upper()
return mode in ("SPAN_ONLY", "SPAN_AND_EVENT")
def lookup_customer(email):
return {"customer_id": "c-17", "email": email}
def find_charges(customer_id, card_number):
raise LookupError(f"no charges on card {card_number} in the last 30 days")
TOOLS = {"lookup_customer": lookup_customer, "find_charges": find_charges}
def call_model(model, messages):
attrs = {"gen_ai.operation.name": "chat", "gen_ai.provider.name": PROVIDER,
"gen_ai.request.model": MODEL}
with tracer.start_as_current_span(f"chat {MODEL}", kind=SpanKind.CLIENT,
attributes=attrs) as span:
resp = model.create(MODEL, messages)
span.set_attribute("gen_ai.response.model", resp["model"])
span.set_attribute("gen_ai.response.finish_reasons", [resp["finish_reason"]])
usage = resp["usage"] # read token counts from the response, not an estimate
span.set_attribute("gen_ai.usage.input_tokens", usage["input_tokens"])
span.set_attribute("gen_ai.usage.output_tokens", usage["output_tokens"])
return resp["reply"]
def run_tool(call_id, name, args):
attrs = {"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": name,
"gen_ai.tool.call.id": call_id}
with tracer.start_as_current_span(f"execute_tool {name}", kind=SpanKind.INTERNAL,
attributes=attrs) as span:
if capture_content():
span.set_attribute("gen_ai.tool.call.arguments", redact(args))
try:
result = TOOLS[name](**args)
except Exception as exc: # the model gets the error; the span records it
message = redact_text(str(exc)) # error text often repeats the input
span.record_exception(exc, attributes={
"exception.message": message,
"exception.stacktrace": redact_text(traceback.format_exc()),
})
span.set_status(Status(StatusCode.ERROR, message))
span.set_attribute("error.type", type(exc).__qualname__)
return {"error": str(exc)}
if capture_content():
span.set_attribute("gen_ai.tool.call.result", redact(result))
return {"result": result}
def run_agent(model, question, max_turns=5):
with tracer.start_as_current_span(f"invoke_agent {AGENT}", attributes={
"gen_ai.operation.name": "invoke_agent", "gen_ai.agent.name": AGENT}):
messages = [{"role": "user", "content": question}]
for _ in range(max_turns):
reply = call_model(model, messages)
if not reply["tool_calls"]:
return reply["content"]
messages.append({"role": "assistant", "content": reply})
for call_id, name, args in reply["tool_calls"]:
out = run_tool(call_id, name, args)
messages.append({"role": "tool", "name": name, "content": out})
raise RuntimeError(f"no answer after {max_turns} turns")03. Lab: Run the Instrumented Loop and Read Its Spans
In this lab you run the loop above with the real OpenTelemetry SDK against a scripted model, print the exported spans as a tree, switch content capture on, and test that no secret is exported. One tool fails on purpose, so you also see an error span.
You need Python 3.12 or later and opentelemetry-sdk 1.45.2. Tested with Python 3.12.13. No API key is needed.
Step 1: install the SDK. Create the folder and a virtual environment, install the SDK and check its version. On Windows, use .venv\Scripts\python instead of .venv/bin/python.
mkdir spans-lab && cd spans-lab
python3 -m venv .venv
.venv/bin/pip install "opentelemetry-sdk==1.45.2"
.venv/bin/python -c "import opentelemetry.sdk.version as v; print(v.__version__)"1.45.2Step 2: add the files. Save redact.py and traced_agent.py from the section above, plus the three files below. telemetry.py sets a TracerProvider with a SimpleSpanProcessor and an InMemorySpanExporter, so finished spans stay in memory where the runner can read them. In production you would use a BatchSpanProcessor with an OTLP exporter (package opentelemetry-exporter-otlp). fake_llm.py is a scripted model that reports token usage the way an API does. IDs are random on every run, so run_spans_lab.py rebuilds the tree from parent IDs and prints only names, attributes and a count of traces, which do not change.
"""Configure the OpenTelemetry SDK once, before the agent creates any span."""
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
InMemorySpanExporter,
)
exporter = InMemorySpanExporter() # keeps finished spans in memory for the lab
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
trace.set_tracer_provider(provider)"""A scripted chat model that reports usage like an API, so no key is needed."""
import json
import math
QUESTION = ("Customer [email protected] says card 4111 1111 1111 1111 "
"was charged twice. Please check.")
CARD = "4111 1111 1111 1111" # a standard test card number, not a real one
def tokens(obj):
return math.ceil(len(json.dumps(obj)) / 4)
class ScriptedChatModel:
def create(self, model, messages):
seen = [m["name"] for m in messages if m["role"] == "tool"]
if "lookup_customer" not in seen:
calls = [("call_1", "lookup_customer", {"email": "[email protected]"})]
elif "find_charges" not in seen:
args = {"customer_id": "c-17", "card_number": CARD}
calls = [("call_2", "find_charges", args)]
else:
calls = []
content = None if calls else "No recent charges found; passing to billing."
reply = {"content": content, "tool_calls": calls}
return {"model": model, "reply": reply,
"finish_reason": "tool_calls" if calls else "stop",
"usage": {"input_tokens": 400 + tokens(messages),
"output_tokens": tokens(reply)}}"""Run the agent once and print the exported spans as a tree."""
import sys
from telemetry import exporter # first: sets the tracer provider
from fake_llm import QUESTION, ScriptedChatModel
from traced_agent import run_agent
print("answer:", run_agent(ScriptedChatModel(), QUESTION))
spans = exporter.get_finished_spans()
only = sys.argv[1] if len(sys.argv) > 1 else "" # e.g. "execute_tool"
def show(span, depth=0):
if depth == 0 or span.name.startswith(only):
pad = " " * depth
print(f"{pad}{span.name} [{span.kind.name}, {span.status.status_code.name}]")
for key, value in span.attributes.items():
print(f"{pad} {key} = {value!r}")
for event in span.events: # the exception event added by record_exception
print(f"{pad} event: {event.attributes['exception.message']}")
children = [s for s in spans
if s.parent is not None and s.parent.span_id == span.context.span_id]
for child in sorted(children, key=lambda s: s.start_time):
show(child, depth + 1)
show(next(s for s in spans if s.parent is None))
used = sum(s.attributes.get("gen_ai.usage.input_tokens", 0)
+ s.attributes.get("gen_ai.usage.output_tokens", 0) for s in spans)
traces = len({s.context.trace_id for s in spans})
errors = [s.name for s in spans if s.status.status_code.name == "ERROR"]
print(f"spans={len(spans)} traces={traces} tokens={used} error_spans={errors}")Step 3: run the agent with content capture off, the default.
.venv/bin/python run_spans_lab.pyanswer: No recent charges found; passing to billing.
invoke_agent SupportTriageAgent [INTERNAL, UNSET]
gen_ai.operation.name = 'invoke_agent'
gen_ai.agent.name = 'SupportTriageAgent'
chat gpt-6-luna [CLIENT, UNSET]
gen_ai.operation.name = 'chat'
gen_ai.provider.name = 'openai'
gen_ai.request.model = 'gpt-6-luna'
gen_ai.response.model = 'gpt-6-luna'
gen_ai.response.finish_reasons = ('tool_calls',)
gen_ai.usage.input_tokens = 430
gen_ai.usage.output_tokens = 24
execute_tool lookup_customer [INTERNAL, UNSET]
gen_ai.operation.name = 'execute_tool'
gen_ai.tool.name = 'lookup_customer'
gen_ai.tool.call.id = 'call_1'
chat gpt-6-luna [CLIENT, UNSET]
gen_ai.operation.name = 'chat'
gen_ai.provider.name = 'openai'
gen_ai.request.model = 'gpt-6-luna'
gen_ai.response.model = 'gpt-6-luna'
gen_ai.response.finish_reasons = ('tool_calls',)
gen_ai.usage.input_tokens = 493
gen_ai.usage.output_tokens = 31
execute_tool find_charges [INTERNAL, ERROR]
gen_ai.operation.name = 'execute_tool'
gen_ai.tool.name = 'find_charges'
gen_ai.tool.call.id = 'call_2'
error.type = 'LookupError'
event: no charges on card [CARD] in the last 30 days
chat gpt-6-luna [CLIENT, UNSET]
gen_ai.operation.name = 'chat'
gen_ai.provider.name = 'openai'
gen_ai.request.model = 'gpt-6-luna'
gen_ai.response.model = 'gpt-6-luna'
gen_ai.response.finish_reasons = ('stop',)
gen_ai.usage.input_tokens = 565
gen_ai.usage.output_tokens = 20
spans=6 traces=1 tokens=1563 error_spans=['execute_tool find_charges']The tree tells the causal story. All six spans share one trace, and each model and tool span is a child of the agent span. The second model call asked for find_charges; that tool span has status ERROR, an error.type of LookupError and an exception event. The agent still answered, so the root span is not an error: the trace shows that the answer was given without charge data, which a plain success log would hide. The token total, 1,563, adds up what each response reported. No email address or card number appears anywhere: content capture is off, and the error text was redacted.
Step 4: opt in to content capture. Set the variable for one run and show only the tool spans. In PowerShell, run $env:OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT = "SPAN_ONLY" first.
OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT=SPAN_ONLY \
.venv/bin/python run_spans_lab.py execute_toolanswer: No recent charges found; passing to billing.
invoke_agent SupportTriageAgent [INTERNAL, UNSET]
gen_ai.operation.name = 'invoke_agent'
gen_ai.agent.name = 'SupportTriageAgent'
execute_tool lookup_customer [INTERNAL, UNSET]
gen_ai.operation.name = 'execute_tool'
gen_ai.tool.name = 'lookup_customer'
gen_ai.tool.call.id = 'call_1'
gen_ai.tool.call.arguments = {'email': '[EMAIL]'}
gen_ai.tool.call.result = {'customer_id': 'c-17', 'email': '[EMAIL]'}
execute_tool find_charges [INTERNAL, ERROR]
gen_ai.operation.name = 'execute_tool'
gen_ai.tool.name = 'find_charges'
gen_ai.tool.call.id = 'call_2'
gen_ai.tool.call.arguments = {'customer_id': 'c-17', 'card_number': '[REDACTED]'}
error.type = 'LookupError'
event: no charges on card [CARD] in the last 30 days
spans=6 traces=1 tokens=1563 error_spans=['execute_tool find_charges']The arguments and the result are now on the spans, but the email address is [EMAIL] and the card number, found by its key, is [REDACTED]. The model itself still received the real values: redaction changes only what the telemetry stores.
Step 5: test the redaction. The test runs the agent with capture off and on, turns every exported span into JSON, and fails if a secret appears anywhere in it: attributes, status, events or stack traces.
"""Fails if a secret or a personal detail reaches an exported span."""
import os
import unittest
from unittest import mock
from telemetry import exporter
from fake_llm import CARD, QUESTION, ScriptedChatModel
from traced_agent import CAPTURE_VAR, run_agent
SECRETS = ["[email protected]", CARD]
def export(env):
"""Run the agent with these settings; return (span name, span as JSON) pairs."""
exporter.clear()
with mock.patch.dict(os.environ, env):
run_agent(ScriptedChatModel(), QUESTION)
return [(span.name, span.to_json()) for span in exporter.get_finished_spans()]
def leaks(spans):
return [(name, s) for name, text in spans for s in SECRETS if s in text]
def has_arguments(spans):
return any("gen_ai.tool.call.arguments" in text for _, text in spans)
class RedactionTest(unittest.TestCase):
def test_content_is_off_by_default(self):
spans = export({CAPTURE_VAR: "NO_CONTENT"})
self.assertFalse(has_arguments(spans))
self.assertEqual(leaks(spans), [])
def test_captured_content_is_redacted(self):
spans = export({CAPTURE_VAR: "SPAN_ONLY"})
self.assertTrue(has_arguments(spans)) # content was captured...
self.assertEqual(leaks(spans), []) # ...but nothing sensitive in it
if __name__ == "__main__":
unittest.main().venv/bin/python -m unittest test_redaction.py..
----------------------------------------------------------------------
Ran 2 tests in 0.021s
OKStep 6: see the test catch a leak. In run_tool, delete the line that sets "exception.stacktrace" and run the test again. Both tests now fail: the default stack trace ends with the exception message, card number included. Put the line back and the tests pass again.
First extra element 0:
('execute_tool find_charges', '4111 1111 1111 1111')
...
FAILED (failures=2)04. Practice questions
05. Apply it
Apply the same instrumentation to your own agent:
- Name spans by the conventions:
invoke_agent {agent},chat {model}andexecute_tool {tool}, each withgen_ai.operation.name, and record which version of the conventions you follow. - Read
gen_ai.usage.input_tokensandgen_ai.usage.output_tokensfrom each provider response. - Set
gen_ai.tool.call.idon each tool span to the ID from the model response. - Mark failures with
set_status(Status(StatusCode.ERROR, ...))andrecord_exception, not with astatus.codeattribute. - Keep content capture off by default. Where you need it, redact arguments, results and error text first, and add your own sensitive keys and patterns to
redact(). - Run a test like
test_redaction.pyin CI, with inputs that contain fake secrets, so that a new tool or field cannot leak data unnoticed.
06. Review prompt
Without looking back, sketch the span tree of one agent run with two tool calls and name the attributes on each span. Then explain why message and argument content is opt-in, name two places other than content attributes where a secret can still reach a span, and describe how you would test that it does not.
References
- OpenTelemetry GenAI semantic conventions: spans and content capture (Development status)
- OpenTelemetry GenAI semantic conventions: inference spans
- OpenTelemetry GenAI semantic conventions: agent spans
- OpenTelemetry GenAI semantic conventions: execute tool spans
- OpenTelemetry Python: instrumentation, span status and exceptions
- OpenTelemetry: Baggage
- Langfuse documentation
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.