Search IOCombats

Search challenges, guides, questions and articles

Users report your agent sometimes picks the wrong tool or gives a confident wrong answer. How do you trace and debug its decisions?

Advanced12 min interview
Skills tested:
Designing what to record for each agent stepUsing OpenTelemetry-based tracing with the AI SDKCorrelating a user report to a specific run with a run idDiagnosing root causes: context, tool design, tool data or model behaviourTurning production failures into regression test cases

Advertisement

🧩 Scenario

Your order-support agent has tools for searching orders, checking delivery status and starting a return. Some users say it started a return when they only asked about delivery, and others get a confident delivery date that does not match the courier data. The interviewer asks how you would trace and debug these decisions.

Architecture Walkthrough

Think of it like Redux DevTools for the model

When a React app shows the wrong state, you open Redux DevTools and step through each action and the state after it. An agent needs the same timeline. Each step is an "action": the model received some messages, chose tools with some arguments, got results back and moved on. If you record that timeline, a vague bug report becomes a concrete step to inspect.

What to record

Per run: a run id, user or session id (pseudonymised if needed), prompt or instructions version, model id, total tokens, total time, how the run ended (finished, step limit, error, aborted).

Per step: step number, finish reason, the tool calls with their arguments, the tool results or errors, tool execution time, and token usage. In development, also the full messages the model saw.

Use tracing, not just logs

The AI SDK has telemetry built on OpenTelemetry. You register an integration once, and calls produce spans for the run, each step, each model call and each tool execution, with usage attributes. You then send them to any OpenTelemetry-compatible backend. The AI SDK also gives you lifecycle callbacks such as onStepEnd and onToolExecutionEnd for your own logging. The OpenAI Agents SDK has tracing turned on by default in server runtimes, if that is your framework.

Link the user report to the trace

Return the run id to the client and keep it on the message. When a user clicks "report a problem", the report carries the run id, so you can open the exact trace instead of guessing.

Debug by finding the first bad step

For the "started a return when I asked about delivery" bug, read the trace from the top:

  1. Did the model have the right context? Maybe history trimming removed the user's actual question.
  2. Was the tool choice reasonable given the tool descriptions? If startReturn is described as "help with an order", the model may pick it for any order question. Fix the description, and put risky tools behind approval.
  3. Was the tool data right? For the wrong delivery date, check the tool result. If the courier API returned stale data, the model only repeated it.
  4. Did the model ignore correct data? Only now is it a prompt or model issue.

Close the loop

Save the failing input and expected behaviour as an eval case (for example "delivery question must not call startReturn"). Run those cases on every prompt or model change, the same way a bug fix gets a unit test.


Key Code Explained

// instrumentation.ts: register once at server startup
import { registerTelemetry } from 'ai';
import { OpenTelemetry } from '@ai-sdk/otel';

registerTelemetry(new OpenTelemetry()); // exporter setup depends on your OTel backend
// agent.ts
import { ToolLoopAgent, isStepCount } from 'ai';
import { tools } from './tools';
import { log } from './logger'; // your structured logger

export function runOrderAgent(runId: string, prompt: string) {
  const agent = new ToolLoopAgent({
    model: 'anthropic/claude-sonnet-5.5', // example id
    instructions: PROMPT_V7, // keep prompts versioned so traces say which one ran
    tools,
    stopWhen: isStepCount(8),
    telemetry: { functionId: 'order-agent' }, // names the run in your traces

    // Your own compact log, keyed by runId, alongside the OTel spans
    onToolExecutionEnd: ({ toolCall, toolExecutionMs, toolOutput }) => {
      log.info('tool', {
        runId,
        tool: toolCall.toolName,
        input: toolCall.input,
        ok: toolOutput.type === 'tool-result',
        ms: toolExecutionMs,
      });
    },
    onStepEnd: ({ stepNumber, finishReason, usage, toolCalls }) => {
      log.info('step', {
        runId,
        stepNumber,
        finishReason,
        tools: toolCalls.map((c) => c.toolName),
        inputTokens: usage.inputTokens,
        outputTokens: usage.outputTokens,
      });
    },
  });

  return agent.generate({ prompt });
}

const PROMPT_V7 = 'You help customers with orders. Only start a return when the user asks for one.';

The OpenTelemetry spans give you the full timeline in a tracing UI. The callbacks give you a small, searchable log tied to your own runId, which is what the support team will search by. Recording the prompt version means that when behaviour changes after a deploy, you can compare traces from before and after.


Tradeoffs

ApproachGood forLimitation
console.log per stepLocal debuggingNo linking, no timings across services
Structured logs with run idSearching by user reportHard to see the step tree
OpenTelemetry tracesFull timeline, nested tool and model spansNeeds a backend and data controls
Full prompt and output captureExact replay of a bad runPersonal data, storage cost
Eval cases from tracesStopping regressionsNeeds upkeep as the product changes

What Interviewers Actually Check

  • Whether you record decisions (tool choice, arguments, results), not just final answers
  • Whether you can link a user complaint to one specific run
  • Whether you debug by root cause instead of tweaking the prompt blindly
  • Whether you handle personal data in traces responsibly
  • Whether you turn failures into regression tests

Follow-Up Questions

  1. How would you trace an agent that calls subagents, so their spans appear under the parent run?
  2. How would you sample traces in production to control cost without losing rare failures?
  3. What would you change if the trace shows the model called the right tool with wrong arguments?
  4. How would you detect wrong-tool choices automatically instead of waiting for user reports?
  5. How do you compare two prompt versions using stored traces?

Common Candidate Mistakes

  • Answering "I would improve the prompt" before looking at any data.
  • Not recording tool results, so data bugs get blamed on the model.
  • Treating every bad answer as a model problem rather than a context or tool problem.
  • Keeping full traces with personal data indefinitely.
  • Fixing one case without a test, so the bug returns with the next prompt change.

Interview Readiness Checklist

Before you leave this question, make sure you can answer:

  • Can you list what to record per run and per step?
  • Can you enable AI SDK telemetry and add step callbacks?
  • Can you explain how a run id connects the UI to the trace?
  • Can you walk through finding the first bad step and its root cause?
  • Can you describe how a failing run becomes an eval case?

Summary

Agents fail in their decisions, so you need to see those decisions. Record one trace per run with a span per step: what the model saw, which tools it chose with what arguments, what came back, tokens and timings. Use OpenTelemetry-based tracing (the AI SDK supports it) plus a compact log keyed by a run id that the UI sends with bug reports. Debug by finding the first bad step and asking whether the cause was context, tool description, tool data or the model itself. Then save the case as an eval so the fix holds.

Frequently Asked Questions

Is console.log enough to debug an agent?

For local development it is a start, but agent runs have many steps, parallel tool calls and sometimes subagents. You need the steps linked together under one run id, with timings and token counts, which is what tracing gives you. OpenTelemetry is the common standard, and the AI SDK and the OpenAI Agents SDK both document tracing support.

Should traces include the full prompts and user messages?

Full inputs and outputs make debugging far easier, but they can contain personal data. Decide per environment: full content in development, redacted or sampled content in production, with access control and a retention period. The AI SDK lets you turn off recording of inputs and outputs.

How do I know which step caused a wrong answer?

Read the trace from the start and find the first step where the model had wrong or missing information, or made a choice you would not make with the same information. Later steps usually just build on that first mistake.

Advertisement


Stay Updated

Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.

Namaste Dev
Sponsored

Cohort-style courses to go from tutorials to job-ready.

Explore Courses

Advertisement