การบันทึกการติดตามขั้นตอนของตัวแทน
บันทึกทุกขั้นตอนการให้เหตุผล การเรียกใช้เครื่องมือ และผลลัพธ์เพื่อวิเคราะห์ภายหลัง
การบันทึกการติดตามขั้นตอนของตัวแทน เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน
เหตุใดการบันทึกการติดตามจึงจำเป็นสำหรับเอเจนต์
บันทึกมาตรฐานของแอปพลิเคชันจะบันทึกข้อผิดพลาดและเหตุการณ์ ส่วนบันทึกการติดตามของเอเจนต์จะบันทึก การให้เหตุผล: เอเจนต์คิดอะไรในแต่ละขั้นตอน เลือกเครื่องมือใด ใช้อาร์กิวเมนต์ใด และเครื่องมือส่งคืนอะไร
หากไม่มีการบันทึกการติดตาม การแก้ไขข้อบกพร่องของเอเจนต์ก็เหมือนกับการวินิจฉัยปัญหารถยนต์โดยไม่มีแผงหน้าปัด คุณทำได้เพียงคาดเดาเท่านั้น
การตั้งค่าโมดูลการบันทึกของ Python
โมดูล logging ในตัวของ Python เป็นเครื่องมือมาตรฐาน ให้กำหนดค่าตั้งแต่เริ่มต้นเอเจนต์ด้วยรูปแบบที่มีเวลา ระดับ และข้อความ ใช้ระดับ DEBUG สำหรับข้อมูลการติดตาม เพราะสามารถปิดได้ในระบบจริง
import logging
import sys
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
datefmt='%H:%M:%S',
stream=sys.stdout
)
logger = logging.getLogger('myagent')
# Usage:
logger.debug('Step 1: reasoning started')
logger.info('Agent task completed in 5 steps')
logger.warning('Tool returned empty result')
logger.error('Failed to parse tool arguments')
# Output:
# 14:32:01 [DEBUG] myagent: Step 1: reasoning started
# 14:32:03 [INFO] myagent: Agent task completed in 5 stepsการบันทึกแต่ละขั้นตอนของการให้เหตุผล
บันทึกข้อเท็จจริงสำคัญเมื่อเริ่มต้นแต่ละขั้นตอน ได้แก่ หมายเลขขั้นตอน การให้เหตุผลที่ LLM สร้างขึ้น เครื่องมือที่เลือก และอาร์กิวเมนต์ที่ส่งไป วิธีนี้จะสร้างบันทึกกระบวนการตัดสินใจของเอเจนต์ไว้อย่างครบถ้วน
import logging
import json
logger = logging.getLogger('myagent')
def log_step(step: int, thought: str, tool_name: str, tool_args: dict):
logger.debug(
f'Step {step}: '
f'reasoning="{thought[:100]}" '
f'tool={tool_name} '
f'args={json.dumps(tool_args, ensure_ascii=False)[:200]}'
)
# Example usage in the agent loop:
# log_step(
# step=1,
# thought='I need to find the current weather in Tokyo',
# tool_name='get_weather',
# tool_args={'city': 'Tokyo', 'unit': 'celsius'}
# )
if __name__ == '__main__':
import sys
logging.basicConfig(level=logging.DEBUG, format='%(message)s', stream=sys.stdout)
log_step(
step=1,
thought='I need to find the current weather in Tokyo',
tool_name='get_weather',
tool_args={'city': 'Tokyo', 'unit': 'celsius'}
)
การบันทึกผลลัพธ์ของเครื่องมือ
หลังการเรียกใช้เครื่องมือแต่ละครั้ง ให้บันทึกว่าการทำงานสำเร็จหรือไม่ และบันทึกตัวอย่างผลลัพธ์ การบันทึกผลลัพธ์ทั้งหมดอาจมีรายละเอียดมากเกินไป จึงควรตัดทอนให้เหลือ 200 อักขระแรกเพื่อให้อ่านง่าย
import logging
logger = logging.getLogger('myagent')
def log_tool_result(step: int, tool_name: str, result: str, success: bool):
status = 'OK' if success else 'ERROR'
preview = str(result)[:200].replace('\n', ' ')
logger.debug(
f'Step {step} result [{status}]: tool={tool_name} '
f'result_preview="{preview}"'
)
if not success:
logger.warning(f'Tool {tool_name} failed at step {step}')
# Log at the start of the step:
# log_step(step, thought, tool_name, tool_args)
# result = execute_tool(tool_name, tool_args)
# log_tool_result(step, tool_name, result, success=True)
if __name__ == '__main__':
import sys
logging.basicConfig(level=logging.DEBUG, format='%(message)s', stream=sys.stdout)
log_tool_result(1, 'get_weather', '{"temp_c": 18, "condition": "cloudy"}', success=True)
log_tool_result(2, 'get_weather', 'Connection timed out', success=False)
การบันทึกแบบมีโครงสร้างด้วยรูปแบบ JSON
บันทึกข้อความธรรมดาอ่านง่ายแต่ค้นหาได้ยาก ส่วนบันทึก JSON แบบมีโครงสร้างสามารถนำเข้าสู่ระบบรวบรวมบันทึก เช่น Datadog, Splunk และ CloudWatch เพื่อใช้กรองข้อมูล สร้างแดชบอร์ด และตั้งการแจ้งเตือน
import logging
import json
import sys
class JSONFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
log_obj = {
'timestamp': self.formatTime(record),
'level': record.levelname,
'logger': record.name,
'message': record.getMessage()
}
# Add any extra fields attached to the log record
if hasattr(record, 'step'):
log_obj['step'] = record.step
if hasattr(record, 'tool'):
log_obj['tool'] = record.tool
return json.dumps(log_obj)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JSONFormatter())
logger = logging.getLogger('agent_trace')
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logger.setLevel(logging.DEBUG)
logger.debug('Step 3: tool=search_web', extra={'step': 3, 'tool': 'search_web'})
การบันทึกด้วยฟิลด์เพิ่มเติม
ส่ง extra={} ไปกับการเรียกบันทึกเพื่อแนบฟิลด์แบบมีโครงสร้าง ซึ่งเครื่องมือจัดรูปแบบ JSON หรือระบบรวบรวมบันทึกสามารถนำไปใช้กรองข้อมูลและวิเคราะห์ได้
import logging
logger = logging.getLogger('agent_trace')
def log_step_structured(step: int, tool: str, thought: str, args: dict):
logger.debug(
f'Step {step}: tool={tool}',
extra={
'step': step,
'tool': tool,
'thought': thought[:200],
'tool_args': args
}
)
# If using a JSON formatter, this produces:
# {
# 'timestamp': '14:32:01',
# 'level': 'DEBUG',
# 'message': 'Step 3: tool=search_web',
# 'step': 3,
# 'tool': 'search_web',
# 'thought': 'I need to find recent news about...',
# 'args': {'query': 'AI news 2025'}
# }
if __name__ == '__main__':
import sys
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('%(message)s | step=%(step)s tool=%(tool)s'))
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
log_step_structured(3, 'search_web', 'I need to find recent news about...', {'query': 'AI news 2025'})
การบันทึกลงไฟล์
สำหรับเอเจนต์ในระบบจริง ให้บันทึกลงไฟล์เพื่อวิเคราะห์ภายหลัง ใช้ RotatingFileHandler เพื่อจำกัดขนาดไฟล์บันทึกและป้องกันพื้นที่ดิสก์เต็ม
import logging
from logging.handlers import RotatingFileHandler
import sys
logger = logging.getLogger('myagent')
logger.setLevel(logging.DEBUG)
# Console handler — INFO and above
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.INFO)
console.setFormatter(logging.Formatter('%(message)s'))
# File handler — DEBUG and above, rotates at 10MB
file_handler = RotatingFileHandler(
'agent_trace.log',
maxBytes=10 * 1024 * 1024, # 10 MB
backupCount=3
)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s [%(levelname)s] %(message)s'
))
logger.addHandler(console)
logger.addHandler(file_handler)
logger.info('Agent task completed in 5 steps')
logger.debug('Step 1: reasoning started')
การบันทึกรหัสเซสชันสำหรับเอเจนต์ที่มีผู้ใช้หลายคน
เมื่อมีผู้ใช้หรืองานหลายรายการทำงานพร้อมกัน บันทึกอาจปะปนกันได้ ให้แนบรหัสเซสชันหรือรหัสงานกับข้อความบันทึกทุกข้อความ เพื่อให้คุณกรองบันทึกของการทำงานใดการทำงานหนึ่งได้
import logging
import uuid
class SessionLogger:
def __init__(self, name: str):
self.logger = logging.getLogger(name)
self.session_id = str(uuid.uuid4())[:8]
def debug(self, msg: str, **kwargs):
self.logger.debug(f'[session={self.session_id}] {msg}', **kwargs)
def info(self, msg: str, **kwargs):
self.logger.info(f'[session={self.session_id}] {msg}', **kwargs)
def error(self, msg: str, **kwargs):
self.logger.error(f'[session={self.session_id}] {msg}', **kwargs)
# Each agent run gets its own logger with a unique session ID
# log = SessionLogger('myagent')
# log.info(f'Starting task: {query}') # [session=a3f1b290] Starting task: ...
if __name__ == '__main__':
import sys
logging.basicConfig(level=logging.INFO, format='%(message)s', stream=sys.stdout)
log = SessionLogger('myagent')
log.info(f'Starting task: summarize the quarterly report')
การจับเวลาแต่ละขั้นตอน
เพิ่มข้อมูลเวลาในบันทึกของแต่ละขั้นตอนเพื่อระบุจุดคอขวด เครื่องมือใดทำงานช้าที่สุด LLM ใช้เวลานานเท่าใดในการให้เหตุผล ข้อมูลนี้ช่วยชี้แนวทางการปรับปรุงประสิทธิภาพ
import time
import logging
logger = logging.getLogger('myagent')
def timed_tool_call(tool_name: str, tool_fn, args: dict) -> str:
start = time.perf_counter()
try:
result = tool_fn(**args)
elapsed = time.perf_counter() - start
logger.debug(f'Tool {tool_name} completed in {elapsed:.2f}s')
return result
except Exception as e:
elapsed = time.perf_counter() - start
logger.error(f'Tool {tool_name} failed in {elapsed:.2f}s: {e}')
raise
# In the agent loop:
# result = timed_tool_call('search_web', search_web, {'query': 'Python'})
# Logs: Tool search_web completed in 1.34s
if __name__ == '__main__':
import sys
logging.basicConfig(level=logging.DEBUG, format='%(message)s', stream=sys.stdout)
def search_web(query):
return f'3 results for {query}'
result = timed_tool_call('search_web', search_web, {'query': 'Python'})
print('Tool result:', result)
รูปแบบการติดตามขั้นตอนฉบับสมบูรณ์
ต่อไปนี้คือรูปแบบการบันทึกการติดตามสำหรับขั้นตอนของเอเจนต์ที่พร้อมใช้ในระบบจริงอย่างสมบูรณ์ ทุกขั้นตอนจะบันทึกหมายเลข การให้เหตุผล การเลือกเครื่องมือ อาร์กิวเมนต์ ตัวอย่างผลลัพธ์ และเวลา ทำให้คุณมองเห็นการทำงานของเอเจนต์ได้อย่างครบถ้วน
import time
import logging
import json
logger = logging.getLogger('myagent')
def trace_step(step_num: int, thought: str, tool: str, args: dict, execute_fn):
# Log decision
logger.debug(
f'Step {step_num}: thought="{thought[:80]}" tool={tool} '
f'args={json.dumps(args)[:100]}'
)
# Execute with timing
t0 = time.perf_counter()
try:
result = execute_fn(tool, args)
elapsed = time.perf_counter() - t0
preview = str(result)[:100].replace('\n', ' ')
logger.debug(f'Step {step_num} done in {elapsed:.2f}s: "{preview}"')
return result
except Exception as e:
elapsed = time.perf_counter() - t0
logger.error(f'Step {step_num} failed in {elapsed:.2f}s: {e}')
return f'ERROR: {e}'
if __name__ == '__main__':
import sys
logging.basicConfig(level=logging.DEBUG, format='%(message)s', stream=sys.stdout)
def execute_fn(tool, args):
return f'42 (from {tool})'
trace_step(1, 'I should compute the answer', 'calculator', {'expr': '6*7'}, execute_fn)
การปิดบันทึกในระบบจริง
บันทึกการติดตามเพื่อแก้ไขข้อบกพร่องอาจมีข้อมูลอ่อนไหว เช่น ข้อความค้นหาและการตอบกลับจาก API และอาจมีรายละเอียดมากเกินไป ในระบบจริง ให้ตั้งระดับบันทึกเป็น INFO หรือ WARNING เพื่อระงับบันทึกการติดตามระดับแก้ไขข้อบกพร่อง ใช้ตัวแปรสภาพแวดล้อมเพื่อควบคุมระดับดังกล่าว
import os
import logging
import sys
# Read log level from environment variable
log_level_str = os.environ.get('LOG_LEVEL', 'INFO').upper()
log_level = getattr(logging, log_level_str, logging.INFO)
logging.basicConfig(level=log_level, stream=sys.stdout)
logger = logging.getLogger('myagent')
# Development: LOG_LEVEL=DEBUG python agent.py -> full traces
# Production: LOG_LEVEL=WARNING python agent.py -> only warnings/errors
# Default: LOG_LEVEL not set -> INFO level
logger.debug('This only appears in DEBUG mode')
logger.info('This appears in INFO and DEBUG modes')
logger.warning('This always appears')ทดสอบความรู้: การบันทึกการติดตาม
ทดสอบความเข้าใจของคุณเกี่ยวกับการบันทึกการติดตามสำหรับขั้นตอนของเอเจนต์
สรุป: การบันทึกการติดตามสำหรับขั้นตอนของเอเจนต์
ขณะนี้คุณมีกลยุทธ์การบันทึกการติดตามสำหรับเอเจนต์อย่างครบถ้วนแล้ว:
- ใช้
logging.basicConfig(level=DEBUG)เพื่อเปิดใช้บันทึกระดับการติดตาม - บันทึกหมายเลขขั้นตอน การให้เหตุผล ชื่อเครื่องมือ และอาร์กิวเมนต์ในแต่ละขั้นตอน
- บันทึกผลลัพธ์ของเครื่องมือพร้อมตัวอย่างผลลัพธ์และสถานะสำเร็จหรือไม่สำเร็จ
- ใช้การจัดรูปแบบ JSON สำหรับบันทึกแบบมีโครงสร้างที่ค้นหาได้
- แนบรหัสเซสชันสำหรับเอเจนต์ที่มีผู้ใช้หลายคนหรือทำงานพร้อมกัน
- เพิ่มข้อมูลเวลาเพื่อระบุขั้นตอนที่ทำงานช้า
- ควบคุมรายละเอียดของบันทึกด้วยตัวแปรสภาพแวดล้อม
LOG_LEVEL
คำถามที่พบบ่อย
บทเรียน “การบันทึกการติดตามขั้นตอนของตัวแทน” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การบันทึกการติดตามขั้นตอนของตัวแทน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การบันทึกการติดตามขั้นตอนของตัวแทน”
บันทึกทุกขั้นตอนการให้เหตุผล การเรียกใช้เครื่องมือ และผลลัพธ์เพื่อวิเคราะห์ภายหลัง คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การบันทึกการติดตามขั้นตอนของตัวแทน” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม
ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ความล้มเหลวทั่วไปของลูปตัวแทน
- การบันทึกการติดตามขั้นตอนของตัวแทน
- การตรวจจับและหยุดลูปไม่สิ้นสุด
- เทคนิคการแก้ไขข้อบกพร่องแบบเดินทีละขั้น