Step-Through Debugging Techniques
Adding breakpoints, intermediate prints, and using debugger in agent code.
Step-Through Debugging Techniques is a free AI Agents lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Debugging Agents Is Different from Debugging Functions
A function has a clear input and output. An agent has a loop with LLM calls, tool executions, and history mutations — all of which can go wrong in subtle ways.
Step-through debugging lets you pause at each step, inspect the agent's state, and understand exactly what went wrong.
Python's Built-In Debugger: pdb
The Python debugger pdb lets you pause execution, inspect variables, and step through code line by line. Insert import pdb; pdb.set_trace() at any point in the agent loop to drop into an interactive debug session.
import pdb
def run_agent_loop(query: str):
history = []
for step in range(1, 21):
action = decide_action(query, history)
# Drop into debugger at step 3 to inspect state
if step == 3:
import pdb; pdb.set_trace()
# At this point you can:
# (Pdb) print(action) -- inspect current action
# (Pdb) print(history) -- inspect full history
# (Pdb) n -- next line
# (Pdb) c -- continue execution
# (Pdb) q -- quit
result = execute_tool(action['tool'], action['args'])
history.append({'tool': action['tool'], 'result': result})Python 3.7+: The breakpoint() Function
Python 3.7+ includes the built-in breakpoint() function — cleaner than import pdb; pdb.set_trace(). It also respects the PYTHONBREAKPOINT environment variable, which lets you swap in a different debugger.
def run_agent_loop(query: str):
history = []
for step in range(1, 21):
action = decide_action(query, history)
breakpoint() # cleaner than pdb.set_trace()
result = execute_tool(action['tool'], action['args'])
history.append({'tool': action['tool'], 'result': result})
# Disable all breakpoints without changing code:
# PYTHONBREAKPOINT=0 python agent.py
# Use ipdb (better UI) instead:
# PYTHONBREAKPOINT=ipdb.set_trace python agent.py
# pip install ipdbpdb Commands Reference
The most important pdb commands for debugging agent loops:
n— next line (step over)s— step into function callc— continue until next breakpointp expr— print expression valuepp expr— pretty-print (for dicts/lists)l— list source code around current lineq— quit the debugger
# Typical pdb debugging session for an agent loop:
# (Pdb) p step -- print current step number: 3
# (Pdb) pp action -- pretty-print the action dict
# {'type': 'tool', 'tool': 'search_web', 'args': {'query': 'Python docs'}}
# (Pdb) pp history -- see full conversation so far
# (Pdb) p len(history) -- count messages: 6
# (Pdb) n -- execute next line
# (Pdb) p result -- see tool result
# (Pdb) c -- continue to next breakpoint
print('pdb lets you inspect agent state at any point in the loop')Conditional Breakpoints
Break only when a specific condition is true — for example, only when a particular tool is selected or when the step count is high. This avoids stopping at every iteration of a long loop.
def run_agent_loop(query: str):
history = []
for step in range(1, 21):
action = decide_action(query, history)
# Break only if the agent picks the wrong tool
if action.get('tool') == 'calculate' and 'weather' in query.lower():
breakpoint() # This is suspicious — weather shouldn't use calculator
# Break only if we're near the step limit
if step >= 18:
breakpoint() # Why hasn't the agent concluded yet?
result = execute_tool(action['tool'], action['args'])
history.append({'tool': action['tool'], 'result': result})VS Code Debugger for Agent Code
The VS Code Python debugger provides a visual step-through experience with variable inspection panels, call stacks, and watch expressions. Configure a launch.json to run your agent in debug mode.
# .vscode/launch.json
# {
# 'version': '0.2.0',
# 'configurations': [
# {
# 'name': 'Debug Agent',
# 'type': 'python',
# 'request': 'launch',
# 'program': 'agent_cli.py',
# 'args': ['--query', 'What is the weather in Paris?'],
# 'env': {
# 'OPENAI_API_KEY': 'your-key',
# 'LOG_LEVEL': 'DEBUG'
# },
# 'console': 'integratedTerminal'
# }
# ]
# }
# Set breakpoints by clicking the left margin in VS Code
# Press F5 to start debugging, F10 to step over, F11 to step into
print('VS Code debugger provides visual debugging with no code changes needed')Adding a --debug Flag to Your CLI
Add a --debug flag to your agent CLI. When set, it enables verbose logging, prints every step, and optionally drops into pdb on errors. This lets you debug without modifying the source code.
import argparse
import logging
parser = argparse.ArgumentParser()
parser.add_argument('--query', required=True)
parser.add_argument('--debug', action='store_true', help='Enable step-by-step debugging output')
parser.add_argument('--pdb-on-error', action='store_true', help='Drop into pdb on any exception')
args = parser.parse_args()
if args.debug:
logging.basicConfig(level=logging.DEBUG)
print('[DEBUG MODE] Step-by-step output enabled')
try:
result = run_agent(args.query, verbose=args.debug)
print(result['answer'])
except Exception as e:
if args.pdb_on_error:
import pdb; pdb.post_mortem() # debug the crash
else:
raiseStepping Through with a Verbose Mode
A verbose mode prints detailed information about each step to stdout, letting you trace the agent's execution without a debugger. Add a verbose=True flag to your agent loop.
import json
def run_agent(query: str, verbose: bool = False) -> dict:
history = []
for step in range(1, 21):
action = decide_action(query, history)
if verbose:
print(f'\n--- Step {step} ---')
print(f'Action type: {action["type"]}')
if action['type'] == 'tool':
print(f'Tool: {action["tool"]}')
print(f'Args: {json.dumps(action["args"], indent=2)}')
if action['type'] == 'final_answer':
if verbose:
print(f'\nFinal answer: {action["answer"]}')
return {'status': 'ok', 'answer': action['answer']}
result = execute_tool(action['tool'], action['args'])
if verbose:
print(f'Result: {str(result)[:200]}')
history.append({'tool': action['tool'], 'result': result})
return {'status': 'max_steps', 'answer': None}Post-Mortem Debugging with pdb.post_mortem()
When an agent crashes with an exception, pdb.post_mortem() opens the debugger at the exact point of failure, with the call stack preserved. This is invaluable for understanding crashes without having to reproduce them.
import pdb
import sys
import traceback
def run_agent_with_postmortem(query: str, debug: bool = False) -> dict:
try:
return run_agent(query)
except Exception as e:
if debug:
print(f'\nAgent crashed: {e}')
traceback.print_exc()
print('\nDropping into post-mortem debugger...')
pdb.post_mortem() # opens debugger at the crash site
return {'status': 'crashed', 'error': str(e)}
else:
raise
# Usage:
# python agent.py --query 'test' --pdb-on-errorInspecting Message History in the Debugger
The most useful thing to inspect during agent debugging is the conversation history. Use pdb's pp command to pretty-print it, or iterate through it to understand what the agent has seen so far.
# Inside a pdb session, common inspection commands:
# Print the full history:
# (Pdb) pp history
# Print only user and assistant messages:
# (Pdb) pp [m for m in history if m['role'] in ('user', 'assistant')]
# Count messages:
# (Pdb) p len(history)
# Find tool calls in history:
# (Pdb) pp [m for m in history if m.get('role') == 'tool']
# Print the last message:
# (Pdb) pp history[-1]
# Print total token estimate (rough):
# (Pdb) p sum(len(str(m)) for m in history)
print('History inspection is the key to understanding agent state')Step-Through Simulation Without LLM Calls
For rapid iteration, build a simulation mode where you manually specify what action the agent takes at each step. This lets you test your tool execution and history management without making any LLM API calls.
def run_agent_simulation(query: str, scripted_actions: list) -> dict:
'Simulate agent steps without LLM calls, using pre-defined actions'
history = []
for step, action in enumerate(scripted_actions, 1):
print(f'Step {step}: {action}')
if action['type'] == 'final_answer':
return {'status': 'ok', 'answer': action['answer'], 'steps': step}
result = execute_tool(action['tool'], action['args'])
print(f' Result: {str(result)[:100]}')
history.append({'tool': action['tool'], 'result': result})
return {'status': 'script_exhausted', 'history': history}
# Test tool execution logic without any LLM:
# result = run_agent_simulation('test', [
# {'type': 'tool', 'tool': 'search_web', 'args': {'query': 'Python'}},
# {'type': 'final_answer', 'answer': 'Python is a programming language.'}
# ])Knowledge Check: Step-Through Debugging
Test your understanding of debugging techniques for agent code.
Recap: Step-Through Debugging Techniques
You now have a full debugging toolkit for agent loops:
- Use
breakpoint()(Python 3.7+) orimport pdb; pdb.set_trace()for interactive debugging - Use conditional breakpoints to stop only when something suspicious happens
- Configure VS Code launch.json to debug with a graphical interface
- Add
--debugand--pdb-on-errorCLI flags for on-demand debugging - Use
pdb.post_mortem()to inspect crashes after they occur - Build simulation mode to test tool logic without LLM calls
- Use verbose mode to trace execution without pausing
Frequently asked questions
Is the “Step-Through Debugging Techniques” lesson free?
Yes — the full text of “Step-Through Debugging Techniques” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “Step-Through Debugging Techniques”?
Adding breakpoints, intermediate prints, and using debugger in agent code. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Step-Through Debugging Techniques” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Common Agent Loop Failures
- Trace Logging for Agent Steps
- Detecting and Breaking Infinite Loops
- Step-Through Debugging Techniques