DEV Community

Cover image for Agent Observability: What to Record When Tracing Decisions and Tool Calls
Shaheryar Yousaf
Shaheryar Yousaf

Posted on

Agent Observability: What to Record When Tracing Decisions and Tool Calls

TL;DR for devs

  • A final answer alone cannot tell you why the agent failed.
  • Record run and version metadata, tool activity, state transitions, usage and outcome categories.
  • Use stable event names and record retries and timeouts.
  • Treat traces as sensitive data: redact at the source and keep secrets out of logs.
  • Connect traces to evaluations so failures become new test cases.

Trace fields, a Python pattern, privacy limits and common logging mistakes

A customer reports that an AI assistant gave the wrong delivery date. The final response says, “Your package arrives Friday.” But what happened behind that sentence? Did the agent query the right order? Did the shipping API return an outdated estimate? Did the model misread the result? Or did a retry overwrite a correct answer with stale information?

Without visibility into the agent’s steps, debugging becomes guesswork. Agent observability provides a way to inspect the application’s behavior across model calls, tools, state changes, and handoffs. It helps teams diagnose failures, understand latency and cost, and improve the system with evidence.

This guide explains what to observe, how traces help, what to log carefully, and how to use Python to capture a basic tool-call trace.

What Does Observability Mean for an AI Agent?

Observability is the ability to understand a system’s internal behavior from the outputs and records it produces. For an AI agent, that includes more than a request and a final answer. A task may involve:

  • The user’s request and relevant context.
  • The model configuration and prompt version.
  • Tool definitions available at the time.
  • Tool requests and validated arguments.
  • Results returned by APIs or functions.
  • Handoffs between specialists.
  • Approval pauses and state changes.
  • Errors, retries, latency, and token usage.
  • The final response and completion status.

A trace groups the events for one task. Individual events or spans represent steps within it. The trace should help answer operational questions: What ran? In what order? How long did it take? What failed? What data was passed between components?

OpenAI’s tracing guide and observability and usage guide describe inspecting model responses, tool calls, delegated work, and usage for supported agent workflows. The exact tooling varies, but the underlying need is common across agent architectures.

Why the Final Answer Is Not Enough

Suppose an agent says, “I couldn’t find your order.” That answer could represent several different situations:

  • The order number was invalid.
  • The account did not have access to that order.
  • The order service timed out.
  • The model failed to select the lookup tool.
  • The application rejected malformed arguments.

Those failures require different fixes. A trace can show whether the tool was called, what status it returned, and whether the model accurately represented the result. It can also reveal hidden inefficiency, such as calling the same search tool five times for one question.

Observability also supports user trust. A concise status summary—“I checked the order service, but it timed out before returning a status”—is more informative than a generic apology. Internally, traces can help developers reproduce and resolve the issue.

What to Record in a Trace

A useful agent trace should capture the structure of a run without storing every piece of sensitive content indefinitely.

Request and task metadata

Record a run ID, timestamp, application version, model identifier, prompt or policy version, and a safe user or tenant identifier. Use these fields to group and compare runs without exposing unnecessary identity information.

Tool activity

For each tool call, record its name, start time, duration, outcome, and a safe representation of the validated arguments. Track whether the call was allowed, rejected, retried, or paused for approval.

State transitions

Capture whether the run moved from received to executing, waiting for clarification, pending approval, completed, or failed. This is especially helpful for long-running tasks that may resume later.

Usage and performance

Measure model-call count, input and output tokens where available, tool latency, total duration, and cost estimates. A task may be accurate but too slow or expensive for the user experience you intend.

Outcome and error category

Distinguish success, no result, user clarification needed, approval pending, and system failure. Use stable error categories so you can group incidents over time.

A Simple Python Trace Pattern

The example below uses a local list to demonstrate the idea. A production system would write trace events to an approved observability backend and apply its retention and access controls.

from datetime import datetime, timezone
from time import perf_counter
from uuid import uuid4


def run_tool_with_trace(tool_name: str, function, **arguments):
    trace_id = str(uuid4())
    started_at = datetime.now(timezone.utc).isoformat()
    start = perf_counter()

    event = {
        "trace_id": trace_id,
        "tool": tool_name,
        "started_at": started_at,
        "argument_keys": sorted(arguments.keys()),
    }

    try:
        result = function(**arguments)
        event["status"] = "success"
        return result, event
    except Exception as exc:
        event["status"] = "error"
        event["error_type"] = type(exc).__name__
        raise
    finally:
        event["duration_seconds"] = round(perf_counter() - start, 3)
        # Send `event` to your trace backend here.
Enter fullscreen mode Exit fullscreen mode

This pattern records the tool name, timing, and error category while avoiding raw argument values. Depending on the application, developers may need selected values for debugging, but they should be redacted or access-controlled. Avoid logging passwords, API keys, payment details, or full private documents.

Connect Traces to Evaluations

A trace is most useful when it can become a learning loop. When a failure occurs, identify which step caused it, then add a scenario to your evaluation set. If the agent chose an update tool when a read-only lookup was intended, create a test for similar phrasing. If a timeout caused a false completion message, test that error path explicitly.

You can compare traces before and after a change to see whether the system improved. Useful measures include:

  • Tool-selection accuracy.
  • Invalid-argument rate.
  • Tool-call count per task.
  • Completion rate and escalation rate.
  • Latency by step and overall.
  • Failure and retry rates.
  • Human edits, approvals, and rejections.
  • Cost per completed task.

Avoid a single “agent quality” score that hides trade-offs. A prompt change could reduce tool calls but increase failures. Track separate measures and examine representative traces.

Logging Privacy and Security

Traces can contain user requests, retrieved documents, and tool outputs. Treat them as sensitive operational data.

  • Collect only what you need to debug and evaluate the product.
  • Redact secrets and personal data before storing traces.
  • Restrict trace access to people who need it.
  • Set retention periods and deletion policies.
  • Protect trace exports and dashboards with access controls.
  • Avoid storing raw external content when a content hash or safe summary is enough.

For some applications, storing full prompts and tool results may be necessary for debugging. Make that decision deliberately and align it with the product’s privacy commitments. Observability should not become a reason to retain everything forever.

Common Observability Mistakes

Logging only the final response

This hides tool-selection errors and failed intermediate steps. Trace the run from input to completion.

Capturing too much sensitive data

Full payloads may contain credentials or personal details. Redact at the source and prefer structured metadata.

Using inconsistent event names

If one service calls an outcome “failed” and another calls it “error,” reporting becomes difficult. Define a shared schema and stable categories.

Ignoring retries and timeouts

A trace should show whether a request was retried, how many times, and whether the remote action may have completed. This is crucial for side effects.

Tracking metrics without investigating examples

Aggregate rates can signal a problem, but specific traces help explain it. Review both trends and representative runs.

Treating a trace as proof of correctness

A trace shows recorded behavior. It does not prove the external data was correct or that the outcome was appropriate. Pair observability with tests, access controls, and source verification.

Frequently Asked Questions

What is an agent trace?

A trace is a record of the connected steps in one agent run, such as model calls, tool calls, approvals, errors, and the final outcome.

Do I need to log the model’s full reasoning?

No. Operational visibility usually comes from recording actions, tool inputs and outputs in a privacy-conscious form, timings, state transitions, and errors. A concise action record can be more useful than retaining internal reasoning text.

What should I avoid putting in logs?

Avoid secrets such as API keys and passwords, and minimize personal or sensitive data. If the content is needed for a specific debugging purpose, redact it, restrict access, and apply a retention policy.

How are traces different from application logs?

Application logs record events from individual services. A trace connects related events across a single task, showing their order and duration. Many systems use both.

Can observability reduce AI costs?

It can reveal excessive model calls, repeated tool use, or oversized context. Those findings can support cost improvements, although logging itself does not automatically reduce spending.

Conclusion

Agent observability gives developers a way to understand what happened between a user’s request and the system’s final response. Traces can reveal wrong tool choices, slow APIs, repeated calls, approval delays, and misleading completion messages. They also help teams turn real failures into repeatable evaluation cases.

Start with a trace schema that records run identity, tool names, status, timing, state transitions, and safe error details. Protect sensitive content, define retention, and use traces alongside tests and monitoring. When you can see how an agent reached its result, you can debug it more quickly and improve it with evidence.

References


I write about building AI agents and full-stack AI apps. Follow me for the next one, and tell me in the comments: What's the hardest agent bug you've had to trace, and what log would have helped?

Top comments (0)