Lesson 23 of 39 · Control, Safety and Quality
Observability With OpenTelemetry
Trace agent runs, model calls and tool calls with OpenTelemetry in Agent Framework: configure_otel_providers, sensitive data, custom spans and metrics.
- 9 min read
- Intermediate
- Reviewed
- Explain traces, spans and metrics, and why agents need them
- Turn on tracing with configure_otel_providers and read the spans of a run
- Decide when to record prompts and replies with enable_sensitive_telemetry
- Add your own spans and metrics with get_tracer and get_meter
- Send telemetry to a real backend, and switch instrumentation on and off
Seeing inside a run
An agent run is a small chain of events: a model call, a tool call, another model call. When a customer says "the bot was slow" or "it refunded the wrong booking", you need to see that chain afterwards. Observability means recording it as it happens.
A tracer in plain Python fits in a few lines:
# Tracing in plain Python: every step opens a span, and spans nest like the calls do.
from contextlib import contextmanager
finished = []
depth = 0
@contextmanager
def span(name, **attributes):
global depth
depth += 1
try:
yield
finally:
depth -= 1
# A span is recorded when it ends, so inner spans come out first.
finished.append(" " * depth + name + (f" {attributes}" if attributes else ""))
with span("invoke_agent rental_desk"):
with span("chat model"):
pass
with span("execute_tool refund", booking="B-1042"):
pass
with span("chat model"):
pass
print("\n".join(finished))Agent Framework creates spans like these for you, with the same names.
Turn on tracing
configure_otel_providers() sets up OpenTelemetry for the whole program and switches on Agent Framework's instrumentation. Call it once, at startup. Here the spans go to the console, one line each:
import asyncio
from agent_framework import Agent, tool
from agent_framework.observability import configure_otel_providers
from agent_framework.openai import OpenAIChatClient
from opentelemetry.sdk.trace.export import ConsoleSpanExporter
@tool
def refund(booking_id: str, amount_eur: float) -> str:
"""Refund money for a booking."""
return f"Refunded {amount_eur:.0f} EUR for {booking_id}."
def one_line(span) -> str:
# The console exporter prints full JSON by default; one line per span is easier to read.
return f"span: {span.name}\n"
async def main():
configure_otel_providers(service_name="velo-desk", exporters=[ConsoleSpanExporter(formatter=one_line)])
agent = Agent(
client=OpenAIChatClient(model="MODEL_NAME"),
name="rental_desk",
instructions="You are Velo's rental desk in Porto. Use refund() for refunds.",
tools=[refund],
)
print((await agent.run("Please refund 35 EUR for booking B-1042.")).text)
asyncio.run(main())Done. Refunded 35 EUR for B-1042. span: chat MODEL_NAME span: execute_tool refund span: chat MODEL_NAME span: invoke_agent rental_desk
One run made four spans: two chat spans for the model calls, one execute_tool span for the refund, and the invoke_agent span around them all, named after the agent's name. Spans are printed when they end, so the outer one comes last. Without the formatter, the console exporter prints every span as JSON, with its trace id, timings and attributes such as gen_ai.operation.name, gen_ai.request.model and gen_ai.tool.name.
Sensitive data: prompts, replies and arguments
By default the spans record what happened but not the content: no prompts, no replies, no tool arguments. enable_sensitive_telemetry() adds them, so you can debug a conversation word for word:
import asyncio
from agent_framework import Agent, tool
from agent_framework.observability import configure_otel_providers, enable_sensitive_telemetry
from agent_framework.openai import OpenAIChatClient
from opentelemetry import trace
from opentelemetry.sdk.trace.export import ConsoleSpanExporter
@tool
def refund(booking_id: str, amount_eur: float) -> str:
"""Refund money for a booking."""
return f"Refunded {amount_eur:.0f} EUR for {booking_id}."
def tool_spans(span) -> str:
if not span.name.startswith("execute_tool"):
return ""
arguments = span.attributes.get("gen_ai.tool.call.arguments", "(not recorded)")
return f"{span.name}: arguments {arguments}\n"
async def main():
configure_otel_providers(service_name="velo-desk", exporters=[ConsoleSpanExporter(formatter=tool_spans)])
agent = Agent(
client=OpenAIChatClient(model="MODEL_NAME"),
name="rental_desk",
instructions="You are Velo's rental desk in Porto. Use refund() for refunds.",
tools=[refund],
)
await agent.run("Please refund 35 EUR for booking B-1042.")
trace.get_tracer_provider().force_flush() # print the spans of this run now
enable_sensitive_telemetry() # development only: records prompts, replies and arguments
await agent.run("Please refund 35 EUR for booking B-1042.")
trace.get_tracer_provider().force_flush()
asyncio.run(main())execute_tool refund: arguments (not recorded)
execute_tool refund: arguments {"booking_id": "B-1042", "amount_eur": 35.0}With sensitive data on, the spans also carry gen_ai.input.messages, gen_ai.output.messages, gen_ai.system_instructions, and the tool's gen_ai.tool.call.arguments and gen_ai.tool.call.result. That is everything your customers type. Use it on your own computer and in test environments, not in production. configure_otel_providers(enable_sensitive_data=True) and the ENABLE_SENSITIVE_DATA=true environment variable do the same.
Your own spans and metrics
get_tracer() and get_meter() give you a tracer and a meter on the same providers, so your spans and the framework's end up in one trace. Wrap each chat message in a span, and count what matters to your business:
import asyncio
from agent_framework import Agent
from agent_framework.observability import configure_otel_providers, get_meter, get_tracer
from agent_framework.openai import OpenAIChatClient
from opentelemetry.sdk.metrics.export import ConsoleMetricExporter
from opentelemetry.sdk.trace.export import ConsoleSpanExporter
def metric_names(data) -> str:
names = [m.name for rm in data.resource_metrics for sm in rm.scope_metrics for m in sm.metrics]
return "".join(f"metric: {name}\n" for name in names)
configure_otel_providers(
service_name="velo-desk",
exporters=[ConsoleSpanExporter(formatter=lambda span: f"span: {span.name}\n"), ConsoleMetricExporter(formatter=metric_names)],
)
tracer = get_tracer("velo.desk") # your own spans, next to the framework's
meter = get_meter("velo.desk") # your own metrics
chats_handled = meter.create_counter("velo.chats_handled", unit="1", description="Chat messages answered")
async def handle_chat_message(agent: Agent, chat_id: str, text: str) -> str:
with tracer.start_as_current_span("handle_chat_message") as span:
span.set_attribute("velo.chat_id", chat_id)
reply = await agent.run(text)
chats_handled.add(1, {"desk": "porto"})
return reply.text
async def main():
agent = Agent(
client=OpenAIChatClient(model="MODEL_NAME"),
name="rental_desk",
instructions="You are Velo's rental desk in Porto. A City E costs 35 EUR a day.",
)
print(await handle_chat_message(agent, "chat-asha", "How much does a City E cost?"))
asyncio.run(main())A City E costs 35 EUR a day. metric: gen_ai.client.operation.duration metric: velo.chats_handled span: chat MODEL_NAME span: invoke_agent rental_desk span: handle_chat_message
The agent's spans now sit inside handle_chat_message, which carries the chat id, so you can find every step of one customer's request. Next to your counter, the framework records its own metrics: gen_ai.client.operation.duration for every model call and, when the provider reports usage, gen_ai.client.token.usage.
Sending telemetry somewhere useful
The console is for learning. In real apps, call configure_otel_providers() without exporters and let standard OpenTelemetry environment variables choose the destination: any OTLP collector or dashboard, such as the Aspire Dashboard, Jaeger or Grafana. For Azure Monitor, set up its own OpenTelemetry distro instead; the framework's spans flow into it too.
export OTEL_SERVICE_NAME="velo-desk"
export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4317" # any OTLP collector or dashboard
export ENABLE_CONSOLE_EXPORTERS=falseTwo more switches control the framework's own instrumentation:
enable_instrumentation()turns it on, for example when an environment variable switched it off. It doesn't create exporters: withoutconfigure_otel_providers()or your own OpenTelemetry setup, nothing is recorded anywhere.disable_instrumentation()turns it off for the whole process. The switch is sticky: later calls toenable_instrumentation()are ignored unless you passforce=True.
Common mistakes
These are the spans of one agent run, with their durations. Find out how much of the run was spent waiting for the model, the question tracing answers most often.
spans = [
{"name": "chat MODEL_NAME", "ms": 820},
{"name": "execute_tool refund", "ms": 140},
{"name": "chat MODEL_NAME", "ms": 610},
{"name": "invoke_agent rental_desk", "ms": 1600},
]
# Add up the time of all model calls (names starting with "chat ") and all tool calls
# (names starting with "execute_tool "), and find the length of the whole run (invoke_agent).
model_ms = 0
tool_ms = 0
run_ms = 1
print(f"model: {model_ms} ms")
print(f"tools: {tool_ms} ms")
print(f"model share: {round(100 * model_ms / run_ms)}%")
What does enable_sensitive_telemetry() add to the spans?
Summary
- A trace is the tree of spans of one request; Agent Framework creates
invoke_agent,chatandexecute_toolspans for you. configure_otel_providers()sets up OpenTelemetry once at startup; exporters orOTEL_*environment variables choose where telemetry goes.enable_sensitive_telemetry()records prompts, replies and tool arguments: development only.get_tracer()andget_meter()add your own spans and metrics to the same traces.disable_instrumentation()turns the framework's telemetry off for the process, untilenable_instrumentation(force=True).
Next: Evaluations and Testing.
Finished reading? Tick it off to track your progress.