DEV Community

tanmay kumar chaurasia
tanmay kumar chaurasia

Posted on

Tracing AI Agents: Debugging Agentic Workflows in Production

Building AI agents feels straightforward in development. You prompt a model, connect a few tools, and watch it handle complex tasks. But once deployed, you inevitably run into a wall: the agent fails, and you have no idea why.

Traditional software fails predictably. A stack trace tells you the exact line number and exception type. AI agents, on the other hand, fail non-deterministically. A user query might succeed five times and fail on the sixth because the LLM generated an unexpected JSON schema, called a tool with bad arguments, or lost context across multi-step planning.

Relying on standard print() statements or flat log files quickly turns debugging into guesswork. To make agents production-ready, you need structured tracing.

The Mental Model: Tracing vs. Logging

Instead of viewing an agent run as a series of disconnected log lines, think of it as a tree of operations.

  • Trace: Represents the entire lifespan of a single agent execution, from the initial user input to the final output.
  • Span: Represents an individual unit of work inside that trace. A single trace contains multiple spans: rendering a prompt template, calling an LLM, querying a vector database, or executing a Python tool.

Spans can nest inside each other. If an agent decides to call a tool, that tool execution is a child span inside the larger LLM execution span. This parent-child hierarchy lets you track the exact lineage of every decision your agent makes.

Implementing Tracing in Python

You don't always need complex external platforms to start understanding your context graphs. You can build lightweight tracing wrappers using basic dataclasses or OpenTelemetry semantics.

Here is a practical Python example demonstrating how to wrap agent tool calls and LLM steps into structured spans:

import uuid
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional

@dataclass
class Span:
    name: str
    trace_id: str
    parent_span_id: Optional[str] = None
    span_id: str = field(default_factory=lambda: str(uuid.uuid4())[:8])
    attributes: Dict[str, Any] = field(default_factory=dict)
    status: str = "OK"
    error: Optional[str] = None

class AgentTracer:
    def __init__(self):
        self.spans: List[Span] = []

    def create_span(self, name: str, trace_id: str, parent_span_id: Optional[str] = None) -> Span:
        span = Span(name=name, trace_id=trace_id, parent_span_id=parent_span_id)
        self.spans.append(span)
        return span

# Example usage during agent execution
tracer = AgentTracer()
trace_id = str(uuid.uuid4())

def execute_agent_step(query: str):
    root_span = tracer.create_span("agent_run", trace_id)
    root_span.attributes["user_query"] = query

    try:
        tool_span = tracer.create_span(
            "execute_tool: fetch_pricing", 
            trace_id, 
            parent_span_id=root_span.span_id
        )
        tool_span.attributes["input_sku"] = "ITEM-123"

        # Simulate a tool execution error
        raise ValueError("SKU 'ITEM-123' not found in database")

    except Exception as e:
        tool_span.status = "ERROR"
        tool_span.error = str(e)
        root_span.status = "ERROR"
        root_span.error = f"Child step failed: {str(e)}"

    return tracer.spans
Enter fullscreen mode Exit fullscreen mode

When an error occurs, the tracer captures both the failure state and the exact attributes passed to that specific step.

Capturing Payload State on Failure

The most critical rule of agent observability is that failed spans must retain their context.

When a tool call crashes or an LLM outputs malformed structured data, recording just the exception string isn't enough. You need the exact input payload that was sent, the system prompt at that moment, and the raw text output returned before parsing failed.

def run_llm_step(tracer: AgentTracer, trace_id: str, parent_id: str, prompt: str):
    span = tracer.create_span("llm_call", trace_id, parent_span_id=parent_id)
    span.attributes["prompt"] = prompt

    try:
        # Raw response received from model
        raw_response = '{"action": "search", "query": null}' 
        span.attributes["raw_response"] = raw_response

        # Attempt to parse or validate schema
        if "null" in raw_response:
            raise KeyError("Missing required field 'query' in JSON output")

    except Exception as exc:
        span.status = "ERROR"
        span.error = str(exc)
        # Raw payload remains saved in attributes for debugging
        raise exc
Enter fullscreen mode Exit fullscreen mode

By persisting the raw_response alongside the exception, you instantly spot whether the failure stemmed from model hallucination, poor prompt context, or actual downstream infrastructure downtime.

From Guessing to Knowing

Without tracing, an agent failure leaves you staring at generic error messages like "Agent failed to complete task". You are forced to replay inputs manually, hoping to reproduce the issue.

With structured tracing, that generic error turns into a clear diagnosis: Step 3 (fetch_pricing) failed because Step 2 (llm_call) passed null as the product SKU.

Observability shifts your engineering workflow from guessing why an agent broke to precisely targeting the fix in your prompts, tools, or validation layers.

About me

Tanmay builds AI agents and automation for businesses and is open to freelance projects. Feel free to connect with him on LinkedIn.

Top comments (0)