0Pricing
AI Agents · レッスン

ステップ実行デバッグの手法

エージェントコードにブレークポイントや中間出力を追加し、デバッガーを使用します。

「ステップ実行デバッグの手法」はCoddyKit上の無料AI Agentsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Agents学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Agentsコースには全4レッスンが含まれています。

エージェントのデバッグは関数のデバッグとは異なる

関数には明確な入力と出力があります。一方、エージェントにはLLMの呼び出し、ツールの実行、履歴の変更を含むループがあり、そのどれもが微妙な形で問題を起こす可能性があります。

ステップ実行デバッグを使うと、各ステップで処理を一時停止し、エージェントの状態を調べ、何が問題だったのかを正確に理解できます。

Python組み込みデバッガー:pdb

Pythonデバッガーのpdbを使うと、実行を一時停止し、変数を調べ、コードを1行ずつ実行できます。エージェントループの任意の場所に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以降には、import pdb; pdb.set_trace()よりすっきりと書ける組み込みのbreakpoint()関数が含まれています。また、別のデバッガーに切り替えられる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 ipdb

pdbコマンドリファレンス

エージェントループのデバッグで特に重要なpdbコマンド:

  • n — 次の行へ(ステップオーバー)
  • s — 関数呼び出しにステップイン
  • c — 次のブレークポイントまで続行
  • p expr — 式の値を出力
  • pp expr — 整形して出力(dictやlistの場合)
  • 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

詳細モードでステップ実行

詳細モードでは、各ステップの詳細情報をstdoutに出力するため、デバッガーなしでエージェントの実行を追跡できます。エージェントループに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-errorのCLIフラグを追加し、必要なときにデバッグできるようにします
  • pdb.post_mortem()を使い、クラッシュ後にその内容を調べます
  • LLM呼び出しなしでツールのロジックをテストできるシミュレーションモードを構築します
  • 詳細モードを使い、一時停止せずに実行を追跡します

よくある質問

「ステップ実行デバッグの手法」レッスンは無料ですか?

はい。「ステップ実行デバッグの手法」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Agentsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Agentsコースには全4レッスンが含まれています。

「ステップ実行デバッグの手法」で何を学びますか?

エージェントコードにブレークポイントや中間出力を追加し、デバッガーを使用します。 ブラウザで直接実行するハンズオンコードでAI Agentsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

AI Agentsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAI Agentsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「ステップ実行デバッグの手法」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAI Agentsレッスンでコードを書いて実行できますか?

はい。すべてのAI Agentsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. エージェントループでよくある失敗
  2. エージェントステップのトレースログ
  3. 無限ループの検出と停止
  4. ステップ実行デバッグの手法
← AI Agentsに戻る