entry
No. 11
date

updated
filed under
debugging, tool use, agents
checked against
10 sources

Agent Observability Tracing: What to Log on Every Step

To trace an AI agent, record one trace per run with a span for the agent invocation, a child span for every model call and a child span for every tool call. On each model span, log the model, the provider, token counts (including cached tokens), the finish reason and the response ID. On each tool span, log the tool name, the call ID, how long it took and the error type if it failed. Leave prompts, tool arguments and results out by default and turn them on only where your storage is allowed to hold them. OpenTelemetry's generative AI semantic conventions name all of these fields, so any tracing backend can read them.

This post walks through that shape, gives a working Python example built on the OpenTelemetry SDK, and shows what the OpenAI Agents SDK records for you. The code was run against opentelemetry-sdk 1.45.2 and openai-agents 0.24.0.

Why logs are not enough for agents

A single agent request can make several model calls and several tool calls, and the model decides the order at run time. A flat log of "called model" and "called tool" lines loses the thing you need most when a run goes wrong: which model response asked for which tool, and what happened next. A trace keeps that structure. Each span has a parent, a start time and an end time, so a run reads as a tree you can open in any tracing tool.

That tree answers the questions agent bugs usually raise. Why did this run cost ten times the average? Look at which model spans carried the most input tokens. Why did it time out? Find the slowest tool span. Did it loop on the same call? Count repeated execute_tool spans with the same tool name.

The shape of an agent trace

OpenTelemetry's generative AI conventions define the span types an agent needs. They now live in their own repository, semantic-conventions-genai, and every document there is marked Development, so names can still change. Pin the version you build against.

Three span types cover a typical agent:

  • Invoke agent. For an agent that runs in your own process, the span kind should be INTERNAL and gen_ai.operation.name should be invoke_agent when the model drives the control flow through tool calls. The span name should be invoke_agent {gen_ai.agent.name}. A graph your code defines, such as a LangGraph StateGraph, is reported as invoke_workflow instead.
  • Inference. Each model call is a span named {gen_ai.operation.name} {gen_ai.request.model}, for example chat my-model. Its kind should be CLIENT when the model runs in another process, which is the usual case.
  • Execute tool. Each tool call is a span named execute_tool {gen_ai.tool.name} with kind INTERNAL. The conventions say tools are often executed directly by application code and encourage developers to instrument those calls themselves when no library covers them.

Retries belong inside the span, not beside it. The conventions say that if a request was retried automatically, the span should cover the whole logical operation including all retries. For how many times to retry, and which tool calls are safe to repeat at all, see agent tool retries.

What to log on every step

These are the attributes worth recording on each span. All names come from the conventions.

On every model call:

  • gen_ai.operation.name and gen_ai.provider.name (both required), plus gen_ai.request.model. Set them when you create the span: the conventions list them among the attributes that matter for sampling decisions and should be provided at span creation time.
  • gen_ai.response.id and gen_ai.response.model, so you can match a span to the provider's own records.
  • gen_ai.response.finish_reasons, an array. The conventions say to report error for a position when a finish reason was expected but never came, for example when a stream ended early.
  • gen_ai.usage.input_tokens and gen_ai.usage.output_tokens. The input count should include cached tokens, and the output count should include reasoning tokens. Record gen_ai.usage.cache_read.input_tokens as well, which is how you check whether prompt caching is working.
  • error.type when the call failed, using a low-cardinality value such as the exception class or the provider's error code.

On every tool call:

  • gen_ai.tool.name (required) and gen_ai.tool.call.id, the ID the model supplied. Set the call ID only if the provider gave one.
  • gen_ai.tool.type, for example function.
  • error.type and an error status when the tool failed.

On the run:

  • gen_ai.agent.name. The conventions say it must have low cardinality and should not be a framework default or a type name such as StateGraph.
  • gen_ai.conversation.id, if your app has a real session or thread ID. The conventions say not to invent one: a new UUID, a trace ID or a hash of the request should not be used as a fallback.
  • Total token counts and the number of turns, which make cost and loop problems easy to find.

For dashboards, the conventions also define agent metrics: gen_ai.invoke_agent.duration, gen_ai.invoke_agent.inference_calls and gen_ai.invoke_agent.tool_calls. Calls per run is one of the cheapest early warnings that a prompt change made the agent work harder.

A working example

The example below traces a small support agent. fake_model stands in for a real model API so the script runs without a key; the token numbers it returns are made up for the demo. Replace it with your client call and read the same fields from the real response.

"""A minimal agent loop traced with OpenTelemetry GenAI span names and attributes."""
import json

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
from opentelemetry.trace import SpanKind, Status, StatusCode

exporter = InMemorySpanExporter()  # swap for an OTLP exporter in production
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("support-agent")

MODEL = "my-model"  # the model name you send to the provider
CAPTURE_CONTENT = False  # off by default, as the conventions recommend


def fake_model(messages):
    """Stands in for a real model call: asks for one tool, then answers."""
    if not any(m["role"] == "tool" for m in messages):
        return {"id": "resp_1", "finish_reason": "tool_calls", "input_tokens": 812,
                "cached_tokens": 640, "output_tokens": 41,
                "tool_calls": [{"id": "call_1", "name": "lookup_order",
                                "arguments": '{"order_id": "A-1001"}'}]}
    return {"id": "resp_2", "finish_reason": "stop", "input_tokens": 901,
            "cached_tokens": 768, "output_tokens": 63, "tool_calls": [],
            "text": "Order A-1001 shipped yesterday."}


def lookup_order(order_id: str) -> dict:
    if not order_id.startswith("A-"):
        raise ValueError("unknown order")
    return {"order_id": order_id, "status": "shipped"}


TOOLS = {"lookup_order": lookup_order}


def call_model(messages):
    with tracer.start_as_current_span(
        f"chat {MODEL}",
        kind=SpanKind.CLIENT,
        attributes={  # set at creation time so samplers can see them
            "gen_ai.operation.name": "chat",
            "gen_ai.provider.name": "openai",  # your provider, from the well-known list
            "gen_ai.request.model": MODEL,
        },
    ) as span:
        response = fake_model(messages)
        span.set_attribute("gen_ai.response.id", response["id"])
        span.set_attribute("gen_ai.response.finish_reasons", [response["finish_reason"]])
        span.set_attribute("gen_ai.usage.input_tokens", response["input_tokens"])
        span.set_attribute("gen_ai.usage.cache_read.input_tokens", response["cached_tokens"])
        span.set_attribute("gen_ai.usage.output_tokens", response["output_tokens"])
        return response


def run_tool(call):
    with tracer.start_as_current_span(
        f"execute_tool {call['name']}",
        kind=SpanKind.INTERNAL,
        attributes={
            "gen_ai.operation.name": "execute_tool",
            "gen_ai.tool.name": call["name"],
            "gen_ai.tool.call.id": call["id"],
            "gen_ai.tool.type": "function",
        },
    ) as span:
        if CAPTURE_CONTENT:
            span.set_attribute("gen_ai.tool.call.arguments", call["arguments"])
        try:
            result = TOOLS[call["name"]](**json.loads(call["arguments"]))
        except Exception as exc:
            span.record_exception(exc)
            span.set_attribute("error.type", type(exc).__qualname__)
            span.set_status(Status(StatusCode.ERROR, str(exc)))
            return {"error": str(exc)}  # the model reads this and can recover
        if CAPTURE_CONTENT:
            span.set_attribute("gen_ai.tool.call.result", json.dumps(result))
        return result


def run_agent(user_input: str, conversation_id: str, max_turns: int = 10) -> str:
    with tracer.start_as_current_span(
        "invoke_agent Support",
        kind=SpanKind.INTERNAL,
        attributes={
            "gen_ai.operation.name": "invoke_agent",
            "gen_ai.agent.name": "Support",
            "gen_ai.conversation.id": conversation_id,
            "gen_ai.request.model": MODEL,
        },
    ) as span:
        messages = [{"role": "user", "content": user_input}]
        totals = {"input": 0, "output": 0}
        for turn in range(1, max_turns + 1):
            response = call_model(messages)
            totals["input"] += response["input_tokens"]
            totals["output"] += response["output_tokens"]
            if not response["tool_calls"]:
                break
            for call in response["tool_calls"]:
                result = run_tool(call)
                messages.append({"role": "tool", "tool_call_id": call["id"],
                                 "content": json.dumps(result)})
        span.set_attribute("gen_ai.usage.input_tokens", totals["input"])
        span.set_attribute("gen_ai.usage.output_tokens", totals["output"])
        span.set_attribute("app.agent.turns", turn)  # your own namespace for custom fields
        return response.get("text", "")


if __name__ == "__main__":
    print(run_agent("Where is order A-1001?", conversation_id="conv_123"))
    for s in sorted(exporter.get_finished_spans(), key=lambda s: s.start_time):
        indent = "  " if s.parent else ""
        print(f"{indent}{s.name} {s.status.status_code.name}", dict(s.attributes))

Running it prints the answer and then the finished spans, the two model calls and the tool call nested under the agent span:

Order A-1001 shipped yesterday.
invoke_agent Support UNSET {'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': 'Support', 'gen_ai.conversation.id': 'conv_123', 'gen_ai.request.model': 'my-model', 'gen_ai.usage.input_tokens': 1713, 'gen_ai.usage.output_tokens': 104, 'app.agent.turns': 2}
  chat my-model UNSET {'gen_ai.operation.name': 'chat', 'gen_ai.provider.name': 'openai', 'gen_ai.request.model': 'my-model', 'gen_ai.response.id': 'resp_1', 'gen_ai.response.finish_reasons': ('tool_calls',), 'gen_ai.usage.input_tokens': 812, 'gen_ai.usage.cache_read.input_tokens': 640, 'gen_ai.usage.output_tokens': 41}
  execute_tool lookup_order UNSET {'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': 'lookup_order', 'gen_ai.tool.call.id': 'call_1', 'gen_ai.tool.type': 'function'}
  chat my-model UNSET {'gen_ai.operation.name': 'chat', 'gen_ai.provider.name': 'openai', 'gen_ai.request.model': 'my-model', 'gen_ai.response.id': 'resp_2', 'gen_ai.response.finish_reasons': ('stop',), 'gen_ai.usage.input_tokens': 901, 'gen_ai.usage.cache_read.input_tokens': 768, 'gen_ai.usage.output_tokens': 63}

A few choices in the code are worth calling out.

Errors go on the span and back to the model. When a tool raises, the span records the exception, sets error.type to the exception class and gets an error status. OpenTelemetry's Python docs say spans are Unset by default, meaning they completed without error, and recommend recording exceptions together with setting the status. The tool still returns an error message, so the model can try something else. Calling run_tool with order B-7 produces a span with status ERROR and error.type set to ValueError.

Custom fields get their own prefix. app.agent.turns is not part of the conventions. Keeping your own fields under your own prefix keeps them apart from gen_ai.* names that may be added later.

Use a real exporter in production. InMemorySpanExporter with SimpleSpanProcessor is for tests. To send spans to a backend, add a BatchSpanProcessor around an OTLPSpanExporter from the opentelemetry-exporter-otlp-proto-http package. The OpenTelemetry Python docs show the same setup pattern with a console exporter.

Keep prompts and results out by default

Prompts, model outputs and tool results are the most useful data for debugging and the riskiest to store. The conventions say instrumentations should not capture instructions, inputs or outputs by default and should offer an opt-in. Tool arguments and results, gen_ai.tool.call.arguments and gen_ai.tool.call.result, are opt-in attributes, and the conventions warn they may contain sensitive information. Input and output messages are flagged as likely to contain user and personal data.

The conventions describe three patterns:

  1. Record no content. This is the default.
  2. Record content on the spans, which suits setups where telemetry volume is manageable and either privacy rules don't apply or the storage complies with them, such as pre-production.
  3. Upload content to separate storage and record only a reference on the span. This is the pattern recommended for production when volume or sensitive data is a concern, because the storage can have its own access controls.

In the example, CAPTURE_CONTENT is the switch. Leave it off in production unless the third pattern is in place.

The OpenAI Agents SDK traces for you

The OpenAI Agents SDK has tracing built in and turned on by default. Each Runner.run is wrapped in a trace, and the SDK adds spans for each agent run, each model generation, each function tool call, guardrails and handoffs. Traces go to OpenAI's Traces dashboard, and the docs note that tracing is unavailable for organizations using the APIs under a Zero Data Retention policy.

Two settings are worth changing on day one. First, the docs say trace_include_sensitive_data defaults to True, which means generation spans store model inputs and outputs, and function spans store tool inputs and outputs. Set it to False on the RunConfig, or set the OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATA environment variable to false. Second, set group_id to your conversation ID, so every run in one chat thread is linked:

import logging

from agents import RunConfig, add_trace_processor
from agents.tracing import TracingProcessor

log = logging.getLogger("agent.trace")


class SpanLogger(TracingProcessor):
    """Logs one line per finished span: type, parent and any error, no content."""

    def on_trace_start(self, trace): pass
    def on_trace_end(self, trace): pass
    def on_span_start(self, span): pass

    def on_span_end(self, span):
        log.info("span=%s trace=%s parent=%s type=%s error=%s",
                 span.span_id, span.trace_id, span.parent_id,
                 span.span_data.type, bool(span.error))

    def shutdown(self): pass
    def force_flush(self): pass


add_trace_processor(SpanLogger())  # keeps the default OpenAI exporter too

run_config = RunConfig(
    workflow_name="Customer support",
    group_id="conv_123",  # links every run in one chat thread
    trace_metadata={"tenant": "acme", "release": "2026-11-15"},
    trace_include_sensitive_data=False,  # drop model and tool inputs/outputs
)

add_trace_processor adds a destination and keeps the default OpenAI exporter. set_trace_processors replaces the defaults, so nothing goes to OpenAI unless you include a processor that sends it. The docs add a warning about redaction: processors are independent, so a redaction processor registered before an exporter does not stop that exporter from receiving the original data if redaction fails. If export must depend on redaction, do both inside one exporter of your own and install it with set_trace_processors. In a short-lived worker, call flush_traces() after the trace closes if spans must be exported before the job ends.

For a smaller tree, RunConfig(tracing={"include_task_and_turn_spans": False}) drops the per-run task and per-turn spans while keeping agent, generation, function, guardrail, handoff and custom spans.

Put traces to work

A trace you never read is just a storage bill. Three uses pay for themselves:

  • Cost per run. Sum input tokens across model spans and compare with cached tokens. A run whose context grows every turn is a context budgeting problem, and the spans show which tool result made it grow.
  • Tool failures. Group execute_tool spans by tool name and error.type. A tool that fails often may have a description the model misreads, which why your agent calls the wrong tool covers.
  • Eval cases. Save the trace of every run that failed or hit a limit and turn it into a test in your agent evals.

If your agent pauses for human approval, trace the approval as its own step so the time spent waiting for a person doesn't look like a slow tool.

Checklist

  • One trace per run, with agent, model and tool spans nested under it.
  • Use the gen_ai.* span names and attribute names, and pin the conventions version.
  • Set operation, provider and model when the span is created.
  • Record input, output and cached tokens and the finish reason on every model span.
  • Record tool name, call ID and error.type on every tool span.
  • Set gen_ai.conversation.id only from a real session ID.
  • Leave prompts, arguments and results out unless your storage is cleared for them.
  • In the OpenAI Agents SDK, set trace_include_sensitive_data=False and a group_id.
  • Use a batch processor and an OTLP exporter in production.
  • Turn failed traces into eval cases.

FAQ

What is agent observability?

It is the ability to see what an agent did on each step of a run: which model calls it made, which tools it called, how long each took, what it cost and where it failed. Tracing is the usual way to get it, because a trace keeps the parent and child links between steps.

Are the OpenTelemetry GenAI semantic conventions stable?

No. The documents in the semantic-conventions-genai repository are marked Development, so names can still change. Pin the version you implement and check the changelog before upgrading.

Should I log prompts and completions in traces?

Not by default. The conventions say instrumentations should not capture them by default, and recommend storing content separately with its own access controls in production when sensitive data is involved.

Does the OpenAI Agents SDK record tool inputs and outputs?

Yes, by default. trace_include_sensitive_data defaults to True, so function spans store tool inputs and outputs. Set it to False on RunConfig or with the OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATA environment variable.

What span name should a tool call use?

The conventions say execute_tool {gen_ai.tool.name}, for example execute_tool lookup_order, with span kind INTERNAL.

Sources

Next in the notebook

  1. No. 2AI Agent Calling the Wrong Tool? 7 Causes and How to Fix Them

    A debugging checklist for tool-calling agents: overlapping tools, vague descriptions, ambiguous parameters, noisy output and bad errors, with a fix for each.

  2. No. 7Agent Infinite Loop: How to Debug Agents That Never Stop

    Why AI agents get stuck in infinite loops, and how to stop them: turn caps, token budgets, repeated-call detection, better tool errors and clear stop rules.

  3. No. 13Agent Tool Retries: Timeouts, Backoff and Idempotency Keys

    Retry agent tool calls only when it is safe: per-attempt timeouts, capped backoff with jitter, idempotency keys and errors the model can read and act on.