0Pricing
AI Agents · บทเรียน

เทคนิคการแก้ไขข้อบกพร่องแบบเดินทีละขั้น

เพิ่มจุดหยุด การพิมพ์ค่าระหว่างทาง และใช้เครื่องมือดีบักในโค้ดตัวแทน

เทคนิคการแก้ไขข้อบกพร่องแบบเดินทีละขั้น เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 ipdb

คู่มือคำสั่ง pdb

คำสั่ง 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 สำหรับโค้ดเอเจนต์

ตัวดีบักเกอร์ Python ของ VS Code มอบประสบการณ์การทำงานแบบทีละขั้นตอนผ่านภาพ พร้อมแผงตรวจสอบตัวแปร สแตกการเรียก และนิพจน์เฝ้าดู ให้กำหนดค่า 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')

การเพิ่มแฟล็ก --debug ให้กับ CLI

เพิ่มแฟล็ก --debug ให้กับ CLI ของเอเจนต์ เมื่อเปิดใช้แฟล็กนี้ ระบบจะเปิดใช้การบันทึกข้อมูลแบบละเอียด แสดงทุกขั้นตอน และเลือกเปิด 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

การตรวจสอบประวัติข้อความในตัวดีบักเกอร์

สิ่งที่มีประโยชน์ที่สุดในการตรวจสอบระหว่างการดีบักเอเจนต์คือประวัติการสนทนา ใช้คำสั่ง pp ของ pdb เพื่อแสดงประวัติดังกล่าวในรูปแบบอ่านง่าย หรือวนดูทีละรายการเพื่อทำความเข้าใจว่าเอเจนต์เห็นอะไรมาบ้างแล้ว

# 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

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 เพื่อดีบักผ่านส่วนติดต่อแบบกราฟิก
  • เพิ่มแฟล็ก CLI --debug และ --pdb-on-error เพื่อดีบักเมื่อจำเป็น
  • ใช้ pdb.post_mortem() เพื่อตรวจสอบการหยุดทำงานหลังจากเกิดขึ้นแล้ว
  • สร้างโหมดจำลองเพื่อทดสอบตรรกะของเครื่องมือโดยไม่เรียกใช้ LLM
  • ใช้โหมดรายละเอียดเพื่อติดตามการทำงานโดยไม่หยุดชั่วคราว

คำถามที่พบบ่อย

บทเรียน “เทคนิคการแก้ไขข้อบกพร่องแบบเดินทีละขั้น” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “เทคนิคการแก้ไขข้อบกพร่องแบบเดินทีละขั้น” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “เทคนิคการแก้ไขข้อบกพร่องแบบเดินทีละขั้น”

เพิ่มจุดหยุด การพิมพ์ค่าระหว่างทาง และใช้เครื่องมือดีบักในโค้ดตัวแทน คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “เทคนิคการแก้ไขข้อบกพร่องแบบเดินทีละขั้น” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม

ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ความล้มเหลวทั่วไปของลูปตัวแทน
  2. การบันทึกการติดตามขั้นตอนของตัวแทน
  3. การตรวจจับและหยุดลูปไม่สิ้นสุด
  4. เทคนิคการแก้ไขข้อบกพร่องแบบเดินทีละขั้น
← กลับไปที่ AI Agents