Agent Debugging Techniques

Production-grade guide to agent debugging techniques covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Agent debugging is the practice of diagnosing and resolving issues in autonomous or semi-autonomous software agents—systems that perform tasks on behalf of users or other systems. It matters when agents fail to produce expected outputs, when they miss deadlines, when they diverge from intended behavior, or when they silently degrade over time. Debugging is not a one-time activity; it is the ongoing process of observing, probing, and refining agent behavior from development through deployment and into production.

Tracing Agent Execution Flow

To understand how an agent arrives at a decision or action, begin by capturing a complete execution trace. A trace records every step: input parsing, context retrieval, tool calls, internal state changes, and final output.

Use a structured log format with timestamps, trace IDs, and hierarchical spans. Each agent step should be a log entry with a span_id and parent_span_id. The root span is the agent invocation; child spans are individual actions.

{
  "timestamp": "2024-03-15T10:32:41.123Z",
  "trace_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
  "span_id": "b2c3d4e5-f678-9012-3456-7890abcdef",
  "parent_span_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
  "name": "tool_call",
  "operation": "call_weather_api",
  "start": 1710534761.123,
  "end": 1710534762.456,
  "metadata": {
    "input": {
      "location": "San Francisco",
      "units": "metric"
    },
    "output": {
      "temperature": 15.2,
      "humidity": 76,
      "forecast": [
        {"day": "Today", "high": 17, "low": 12},
        {"day": "Tomorrow", "high": 19, "low": 14}
      ]
    },
    "duration_ms": 1333
  }
}

For agents that process multiple inputs in sequence, use a correlation_id to link logs across multiple invocations. A missing correlation_id leads to fragmented traceability: logs from different agent runs appear isolated, making it hard to track a user’s journey.

Always emit logs at the following levels:

Validating Input and Output Data

Agent behavior often depends on the fidelity of input and output data. A mismatch between expected and actual data types, shapes, or values silently corrupts agent logic.

Start with schema validation using JSON Schema. Define a schema for the agent’s input and output payloads. Validate incoming data before processing:

{
  "type": "object",
  "required": ["query", "context"],
  "properties": {
    "query": { "type": "string", "minLength": 1 },
    "context": {
      "type": "object",
      "properties": {
        "user_id": { "type": "string" },
        "session_id": { "type": "string" },
        "recent_conversations": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "timestamp": { "type": "string", "format": "date-time" },
              "message": { "type": "string" }
            },
            "required": ["timestamp", "message"]
          }
        }
      },
      "required": ["user_id", "session_id"]
    }
  }
}

A common failure: the agent expects context.user_id as a string but receives an integer. The agent proceeds, but downstream components fail. Use jsonschema CLI or jq to validate data directly:

jq -c -S . < input.json | \
  jsonschema -i - -s schema.json

If validation fails, record the error field in the log with the actual JSON, the expected schema, and the validation path:

{
  "level": "error",
  "message": "Input validation failed",
  "details": {
    "schema": "schema.json",
    "actual": {
      "query": "What's the weather?",
      "context": {
        "user_id": 12345,
        "session_id": "s987654321",
        "recent_conversations": []
      }
    },
    "errors": [
      {
        "keyword": "type",
        "message": "Expected string, but got number",
        "params": { "type": "string" },
        "schemaPath": "#/properties/context/properties/user_id/type",
        "instancePath": "#/context/user_id"
      }
    ]
  }
}

When an agent fails to produce a correct output, compare the actual output against a reference. Use diff and jq:

jq -S . < actual_output.json > actual.json
jq -S . < expected_output.json > expected.json
diff -u expected.json actual.json

A subtle but frequent failure: the agent outputs {"status": "success"} but the consumer expects {"status": "SUCCESS"}. Case sensitivity breaks integrations.

Instrumenting Tool and Service Calls

Agents rely on external services—APIs, databases, message queues. Each call introduces a potential failure point.

Record every tool call with a consistent format. Include:

Use HTTP headers to propagate context:

When calling a service, include the full request and response in the log:

{
  "name": "api_call",
  "operation": "fetch_user_profile",
  "start": 1710534762.456,
  "end": 1710534765.123,
  "metadata": {
    "url": "https://api.example.com/v1/profiles/12345",
    "method": "GET",
    "headers": {
      "Authorization": "Bearer abcdef123456",
      "X-Trace-ID": "a1b2c3d4-e5f6-7890-1234-567890abcdef"
    },
    "request_body": null,
    "response_status": 200,
    "response_body": {
      "user_id": 12345,
      "name": "Alice Smith",
      "email": "[email protected]",
      "preferences": {
        "theme": "dark",
        "notifications": true
      }
    },
    "error": null
  }
}

When the response status is not 200, include the error details:

"error": {
  "code": "SERVICE_UNAVAILABLE",
  "message": "User service is temporarily down",
  "details": {
    "retry_after_seconds": 30,
    "backoff": 1.5,
    "service_version": "v2.3.1"
  }
}

Use curl to simulate and test tool calls in isolation:

curl -X GET \
  -H "Authorization: Bearer abcdef123456" \
  -H "X-Trace-ID: a1b2c3d4-e5f6-7890-1234-567890abcdef" \
  "https://api.example.com/v1/profiles/12345"

A silent failure: the agent calls a service, receives a 200 OK, but the response_body is null. The service returned {"success": true} but the agent expected a user object. Validate the response using jq:

curl -s -H "Accept: application/json" \
  "https://api.example.com/v1/profiles/12345" | \
  jq '. | select(.user_id == 12345 and .name == "Alice Smith")'

Debugging Agent State and Memory

Agents often maintain state across multiple interactions. This state may be stored in a database, a cache, or in-memory.

Use psql to inspect the state table directly:

SELECT id, agent_id, state, last_updated
FROM agent_states
WHERE agent_id = 'user123'
ORDER BY last_updated DESC
LIMIT 5;

A common failure: the agent’s internal state is updated but not persisted. The last_updated timestamp is missing, or the state JSON is malformed.

When using a cache (Redis, Memcached), verify that keys exist and values are correct:

redis-cli --raw
> GET "agent:state:user123"
{
  "context": {
    "user_id": "user123",
    "session_id": "sess456",
    "messages": [
      {"role": "user", "content": "Hello"},
      {"role": "agent", "content": "Hi! How can I help?"}
    ]
  },
  "step": "waiting_for_confirmation"
}

If a key is missing, check the agent’s state update logic. A frequent error: the agent updates state but forgets to expire the key, causing stale data to accumulate.

Use systemctl to check if the agent process is running and healthy:

systemctl status agent-worker.service
journalctl -u agent-worker.service -f --since "2024-03-15 10:00"

Check for memory leaks: high CPU, increasing memory usage, or frequent GC pauses. Use top, htop, and pgrep:

htop -p $(pgrep agent-worker)

A sharp edge: the agent updates state but fails to commit the transaction. The database logs show BEGIN, UPDATE, but no COMMIT. The agent crashes after the update but before the commit. Add explicit COMMIT and ROLLBACK blocks in the database transaction.

Diagnosing Agent Decision Logic

When an agent selects a path or makes a choice, the logic behind that decision must be visible.

Log every condition evaluated, every rule applied, and every action taken:

{
  "name": "decision",
  "operation": "select_action",
  "start": 1710534765.123,
  "end": 1710534766.345,
  "metadata": {
    "conditions": [
      {
        "name": "user_is_new",
        "value": true,
        "reason": "User created in last 7 days"
      },
      {
        "name": "has_high_priority_task",
        "value": false,
        "reason": "No tasks with priority 'urgent'"
      }
    ],
    "selected_action": "send_welcome_email",
    "confidence": 0.87,
    "rules_applied": [
      "if user is new, send welcome email",
      "if user has no urgent tasks, suggest onboarding"
    ]
  }
}

When the agent chooses the wrong action, trace the rule evaluation. A typical failure: a rule uses priority == "high" but the data stores priority: "High" (capitalized). Use jq to inspect and validate rule inputs:

jq '.rules[] | select(.condition == "priority == high")' rules.json

For complex decision trees, use a decision_trace field that logs the path taken:

"decision_trace": [
  "root",
  "user_is_new → true",
  "has_high_priority_task → false",
  "selected_action: send_welcome_email"
]

Use grep and awk to extract decision traces:

grep -A 5 -B 2 "decision" logs/*.log | \
  awk '/selected_action/ {print $0; getline; print $0}'

Resolving Agent Failures in Production

When an agent fails in production, use the following workflow:

  1. Identify the failing agent: use journalctl and systemctl to locate logs and processes.
  2. Find the trace ID: extract X-Trace-ID from HTTP headers or logs.
  3. Retrieve the full trace: query a central logging system (ELK, Loki, Datadog) using the trace ID.
  4. Inspect the input and output: validate data against schemas.
  5. Check each tool call: verify responses, status codes, and error details.
  6. Review state and context: query the database or cache.
  7. Reproduce the failure: use curl, psql, and redis-cli to simulate the exact environment.

A common production failure: an agent processes 1000 requests but fails on the 500th. The logs show error: "Context expired", but no details. Use jq to extract the context:

grep "Context expired" logs/2024-03-15.log | \
  jq -r '.context | .session_id'

Then query the session state:

SELECT * FROM agent_sessions
WHERE session_id = 'sess456'
ORDER BY created_at DESC;

This reveals that the session was created 48 hours ago, but the agent expected it to be updated within the last 24 hours.

Always use a debug level log when diagnosing production issues. It reveals subtle state changes that info logs miss. Never assume that “it works” means “it’s correct.”

This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.