단계별 디버깅 기법
에이전트 코드에 중단점과 중간 출력문을 추가하고 디버거를 사용합니다.
단계별 디버깅 기법은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
에이전트 디버깅은 함수 디버깅과 다릅니다
함수에는 명확한 입력과 출력이 있습니다. 에이전트에는 LLM 호출, 도구 실행, 이력 변경이 포함된 루프가 있으며, 이 모든 부분에서 미묘한 방식으로 문제가 발생할 수 있습니다.
단계별 디버깅을 사용하면 각 단계에서 일시 중지하고 에이전트의 상태를 확인하여 정확히 무엇이 잘못되었는지 파악할 수 있습니다.
Python 내장 디버거: pdb
Python 디버거 pdb를 사용하면 실행을 일시 중지하고, 변수를 확인하며, 코드를 한 줄씩 따라갈 수 있습니다. 에이전트 루프의 어느 지점에든 import pdb; pdb.set_trace()를 삽입하면 대화형 디버그 세션으로 진입합니다.
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 이상: breakpoint() 함수
Python 3.7 이상에는 내장 breakpoint() 함수가 포함되어 있어 import pdb; pdb.set_trace()보다 더 깔끔합니다. 또한 PYTHONBREAKPOINT 환경 변수를 따르므로 다른 디버거로 바꿀 수 있습니다.
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 명령어 참조
에이전트 반복문을 디버깅할 때 가장 중요한 pdb 명령어입니다:
n— 다음 줄(건너뛰기)s— 함수 호출 안으로 들어가기c— 다음 중단점까지 계속 실행p expr— 표현식 값 출력pp expr— 형식을 정돈해 출력(딕셔너리/목록에 유용)l— 현재 줄 주변의 소스 코드 나열q— 디버거 종료
# 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')조건부 중단점
특정 조건이 참일 때만 중단하십시오. 예를 들어 특정 도구가 선택되었을 때나 단계 수가 많을 때만 중단할 수 있습니다. 이렇게 하면 긴 반복문이 반복될 때마다 멈추지 않아도 됩니다.
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 디버거
VS Code Python 디버거는 변수 검사 패널, 호출 스택, 감시 표현식을 사용해 시각적으로 단계를 실행할 수 있는 환경을 제공합니다. launch.json을 구성하여 에이전트를 디버그 모드로 실행하십시오.
# .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')CLI에 --debug 플래그 추가하기
에이전트 CLI에 --debug 플래그를 추가하십시오. 이 플래그를 설정하면 상세 로그 기록을 활성화하고 모든 단계를 출력하며, 오류 발생 시 선택적으로 pdb 디버거로 진입합니다. 소스 코드를 수정하지 않고 디버깅할 수 있습니다.
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:
raise상세 출력 모드로 단계별 실행
상세 모드는 각 단계에 대한 자세한 정보를 표준 출력에 표시하므로 디버거 없이 에이전트의 실행을 추적할 수 있습니다. 에이전트 반복문에 verbose=True 플래그를 추가하십시오.
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}pdb.post_mortem()을 사용한 사후 디버깅
에이전트가 예외로 중단되면 pdb.post_mortem()은 호출 스택이 보존된 상태로 실패가 발생한 정확한 지점에서 디버거를 엽니다. 중단을 재현하지 않고도 원인을 이해하는 데 매우 유용합니다.
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-error디버거에서 메시지 기록 검사하기
에이전트를 디버깅할 때 검사할 가장 유용한 내용은 대화 기록입니다. pdb의 pp 명령어로 형식을 정돈해 출력하거나, 기록을 순회하면서 에이전트가 지금까지 본 내용을 파악하십시오.
# 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')LLM 호출 없이 단계별 시뮬레이션
빠르게 반복 개발하려면 각 단계에서 에이전트가 수행할 동작을 직접 지정하는 시뮬레이션 모드를 구현하십시오. 이렇게 하면 LLM API를 호출하지 않고도 도구 실행과 기록 관리를 검증할 수 있습니다.
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.'}
# ])지식 확인: 단계별 디버깅
에이전트 코드의 디버깅 기법에 대한 이해도를 확인하십시오.
복습: 단계별 디버깅 기법
이제 에이전트 반복문을 위한 완전한 디버깅 도구 모음을 갖추었습니다:
- 대화형 디버깅에는
breakpoint()(Python 3.7 이상) 또는import pdb; pdb.set_trace()를 사용하십시오 - 조건부 중단점을 사용하여 의심스러운 상황이 발생할 때만 중단하십시오
- 그래픽 인터페이스로 디버깅하도록 VS Code의 launch.json을 구성하십시오
- 필요할 때 디버깅할 수 있도록
--debug및--pdb-on-errorCLI 플래그를 추가하십시오 - 중단이 발생한 후 검사하려면
pdb.post_mortem()을 사용하십시오 - LLM 호출 없이 도구 로직을 검증할 수 있는 시뮬레이션 모드를 구현하십시오
- 일시 중지 없이 실행을 추적하려면 상세 모드를 사용하십시오
자주 묻는 질문
“단계별 디버깅 기법” 강의는 무료인가요?
네 — “단계별 디버깅 기법” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.
“단계별 디버깅 기법”에서 뭘 배우나요?
에이전트 코드에 중단점과 중간 출력문을 추가하고 디버거를 사용합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Agents을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“단계별 디버깅 기법” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.