How to Debug an AI Agent
Learn practical techniques to debug AI agents: tracing tool calls, logging prompts, testing edge cases, and reproducing failures.
Before you start
You built an AI agent that calls tools, reads files, and makes decisions. It works in your happy-path test, but in production it starts looping, calling the wrong tool, or returning a hallucinated answer. You have no idea why. This article walks through a systematic debugging workflow for AI agents, using a minimal TypeScript example you can run locally.
We assume you have Node.js 18+ and npm installed. We will use the OpenAI SDK, but the techniques apply to any LLM provider. We will build a tiny agent that can fetch weather and calculate dates, then add tracing, logging, and test cases to expose failures.
mkdir agent-debug && cd agent-debug
npm init -y
npm install openai dotenvStep 1: Build a minimal agent loop
Start with a simple agent that decides which tool to call based on the user's request. The core loop is: send the conversation to the model, get a response, if it contains tool calls, execute them and append results, then repeat.
Create a file named agent.ts with the following code. It defines two tools: getWeather and getDate. The agent uses the OpenAI chat completions API with function calling.
import OpenAI from 'openai';
import 'dotenv/config';
const openai = new OpenAI();
const tools = [
{
type: 'function' as const,
function: {
name: 'getWeather',
description: 'Get the current weather for a city',
parameters: {
type: 'object',
properties: { city: { type: 'string' } },
required: ['city'],
},
},
},
{
type: 'function' as const,
function: {
name: 'getDate',
description: 'Get the current date',
parameters: { type: 'object', properties: {} },
},
},
];
async function callTool(name: string, args: any) {
if (name === 'getWeather') {
return `Weather in ${args.city}: sunny, 22C`;
}
if (name === 'getDate') {
return new Date().toISOString();
}
throw new Error(`Unknown tool: ${name}`);
}
async function runAgent(userInput: string) {
const messages: any[] = [{ role: 'user', content: userInput }];
for (let i = 0; i < 5; i++) {
const response = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages,
tools,
});
const message = response.choices[0].message;
messages.push(message);
if (message.tool_calls) {
for (const call of message.tool_calls) {
const result = await callTool(call.function.name, JSON.parse(call.function.arguments));
messages.push({ role: 'tool', tool_call_id: call.id, content: result });
}
} else {
return message.content;
}
}
throw new Error('Max iterations reached');
}
// Example usage
console.log(await runAgent('What is the weather in Paris?'));- Set OPENAI_API_KEY in a .env file before running.
- Run with npx tsx agent.ts to execute TypeScript directly.
- The loop is capped at 5 iterations to avoid infinite loops.
Step 2: Add structured logging
The first debugging step is visibility. You need to see every message, tool call, and result. Add a simple logger that prints the full conversation history at each iteration.
Modify agent.ts to include a log function and call it after each API response.
function log(step: number, messages: any[]) {
console.log(`--- Step ${step} ---`);
for (const m of messages) {
if (m.role === 'assistant' && m.tool_calls) {
console.log(`ASSISTANT: tool_calls=${JSON.stringify(m.tool_calls)}`);
} else if (m.role === 'tool') {
console.log(`TOOL: ${m.name} -> ${m.content}`);
} else {
console.log(`${m.role.toUpperCase()}: ${m.content}`);
}
}
}
// Inside runAgent, after messages.push(message):
log(i, messages);- Log the full message array, not just the final answer.
- Include token usage if available (response.usage) to track cost.
- Use a JSON formatter for machine-readable logs in production.
Step 3: Reproduce the failure with a test harness
When something goes wrong, you need a minimal reproduction. Create a test script that runs the agent with a specific input and asserts the output. This turns a mystery into a repeatable bug.
Write a test file test-agent.ts using Node's built-in test runner.
import { test } from 'node:test';
import assert from 'node:assert';
import { runAgent } from './agent';
test('agent returns weather for Paris', async () => {
const result = await runAgent('What is the weather in Paris?');
assert.match(result, /sunny/);
});
test('agent handles unknown city gracefully', async () => {
const result = await runAgent('Weather in Atlantis?');
assert.ok(result); // just check it doesn't throw
});
test('agent stops after max iterations', async () => {
await assert.rejects(() => runAgent('loop forever'), /Max iterations/);
});- Run with node --test test-agent.ts.
- Add a test for every bug you fix to prevent regression.
- Use a fixed seed or mock the LLM API for deterministic tests.
Step 4: Inspect tool call arguments
A common failure is the model generating malformed arguments. Log the raw arguments string before parsing to catch JSON syntax errors.
Update callTool to log the raw input and wrap JSON.parse in a try-catch.
async function callTool(name: string, argsString: string) {
console.log(`CALL ${name}(${argsString})`);
let args;
try {
args = JSON.parse(argsString);
} catch (e) {
console.error(`Failed to parse args for ${name}: ${argsString}`);
return `Error: invalid arguments`;
}
if (name === 'getWeather') {
if (!args.city) return 'Error: missing city';
return `Weather in ${args.city}: sunny, 22C`;
}
if (name === 'getDate') {
return new Date().toISOString();
}
return `Error: unknown tool ${name}`;
}
// In runAgent, pass call.function.arguments directly:
const result = await callTool(call.function.name, call.function.arguments);- Never assume arguments are valid JSON.
- Return a clear error message to the model so it can recover.
- Consider using a schema validator like zod to enforce types.
Step 5: Trace the decision path with a debugger
For complex failures, step through the loop with a debugger. Use the Node.js inspector to pause at each iteration and inspect variables.
Run your script with --inspect and open Chrome DevTools, or use a VS Code launch configuration.
node --inspect-brk test-agent.ts
# Then open chrome://inspect in Chrome, or attach VS Code debugger.{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Agent",
"program": "${workspaceFolder}/agent.ts",
"runtimeArgs": ["--loader", "tsx"],
"console": "integratedTerminal"
}
]
}- Set breakpoints inside the loop to inspect messages and tool results.
- Use the debug console to evaluate expressions like messages[messages.length-1].
- If using tsx, ensure you have the tsx loader configured.
Step 6: Add a timeout and retry policy
Agents can hang on slow API calls or infinite loops. Add a timeout to each API request and a max retry count.
Use the OpenAI SDK's timeout option and a simple retry wrapper.
const openai = new OpenAI({ timeout: 10000, maxRetries: 2 });
// Or implement a manual timeout with AbortController:
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10000);
try {
const response = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages,
tools,
}, { signal: controller.signal });
} finally {
clearTimeout(timer);
}- Set a reasonable timeout (10-30 seconds) for LLM calls.
- Catch timeout errors and return a friendly message to the user.
- Retry only on transient errors (429, 500, 503), not on 400.
Step 7: Use observability tools
For production, use an observability platform that traces agent steps. You can build a simple trace by logging structured events to stdout, which tools like Langfuse or Helicone can ingest.
Here's a minimal trace format you can emit and later parse.
function trace(event: string, data: any) {
console.log(JSON.stringify({ event, data, timestamp: new Date().toISOString() }));
}
// Usage in runAgent:
trace('agent.start', { input: userInput });
trace('llm.call', { model: 'gpt-4o-mini', messages });
trace('tool.call', { name, args });
trace('tool.result', { name, result });
trace('agent.end', { output: finalAnswer });- Log every external call: LLM, tools, APIs.
- Include a correlation ID to group traces per user request.
- Export traces to a service like Langfuse, Helicone, or your own backend.
Troubleshooting common issues
Here are five failures you will hit and how to fix them.
- Loop: agent keeps calling the same tool. Add a maximum iteration count and log each call to spot the repetition.
- Malformed arguments: model returns invalid JSON. Log the raw string and return an error to the model asking it to retry.
- Wrong tool: model picks the wrong function. Improve tool descriptions and include examples in the system prompt.
- Hallucination: model invents tool results. Verify tool output and add a confidence check before using it.
- Slow responses: API calls take too long. Use streaming or reduce the number of tokens in the prompt.
Recommended setup
For a production agent, I would combine the following: a minimal agent loop with logging, a test harness, a timeout policy, and structured traces. Here is a copy-paste starter for the core loop with logging and error handling.
import OpenAI from 'openai';
const openai = new OpenAI({ timeout: 15000, maxRetries: 2 });
async function runAgent(userInput: string): Promise<string> {
const messages: any[] = [{ role: 'user', content: userInput }];
for (let step = 0; step < 5; step++) {
console.log(`[step ${step}]`);
const response = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages,
tools: [/* your tools */],
});
const message = response.choices[0].message;
messages.push(message);
if (message.tool_calls) {
for (const call of message.tool_calls) {
const result = await executeTool(call.function.name, call.function.arguments);
console.log(`tool ${call.function.name} -> ${result}`);
messages.push({ role: 'tool', tool_call_id: call.id, content: result });
}
} else {
return message.content || '';
}
}
throw new Error('Max iterations reached');
}
async function executeTool(name: string, argsString: string): Promise<string> {
let args;
try {
args = JSON.parse(argsString);
} catch {
return 'Error: invalid JSON arguments';
}
// Implement your tools here
return `Result for ${name}: ${JSON.stringify(args)}`;
}FAQ
Answers to the questions that come up most often on this topic.
- Q: Why does my agent loop forever? A: The model may keep calling a tool because the result does not satisfy the goal. Add a max iteration limit and log each tool call to identify the loop.
- Q: How do I debug a tool that returns wrong data? A: Log the raw tool output and verify it against a known source. Add unit tests for each tool function.
- Q: Can I use a debugger with TypeScript agents? A: Yes, use tsx with node --inspect and a VS Code launch configuration.
- Q: What is the best observability tool for agents? A: Start with structured logs, then integrate a platform like Langfuse or Helicone if you need deeper tracing.
- Q: How do I test agents without spending API credits? A: Mock the LLM API by replacing the openai client with a stub that returns predefined responses.
Next step
Run the test harness with a few edge cases, then add a timeout and structured tracing to your own agent. Start with the logger and test file from this article; they will pay for themselves on the first production incident.
Key takeaways
- Apply one concrete change from this post before collecting more reading.
- Prefer browser-side tools when the work involves secrets, tokens, or PII.
- Document the why next to the how so the next reviewer inherits context.
FAQ
- Who is this guide on ai-agent for?
- Working developers who need a practical take on how to debug an ai agent — not a marketing overview. Skim the sections, apply one tip, then come back when you hit an edge case.
- Do I need an account to use the related tools?
- No. code.live tools run in your browser with no signup. Nothing you paste is uploaded to a server for the client-side utilities linked from this post.
- How often is this article updated?
- This post was published November 24, 2026. Fundamentals stay stable; check linked tool pages and official docs when version-specific behavior matters.