AI Agents ด้วย Hugging Face smolagents
Adel Nehme
VP of AI Curriculum, DataCamp



agent = CodeAgent(
tools=[document_search_tool],
model=model,
planning_interval=3,
max_steps=12
)
planning_interval=3: Agent หยุดพักทุก 3 ขั้นตอน"วางแผนทริปครอบครัว 2 สัปดาห์ที่ยุโรป มีสถานที่ทางประวัติศาสตร์สำหรับผู้ใหญ่และกิจกรรมสนุกสำหรับเด็ก งบไม่เกิน $5000"
[Step 1] ค้นหา "Paris hotels" -> พบโรงแรมระดับหรู (~$4000 รวม)
[Step 2] ค้นหา "Paris attractions for families" -> พบ Eiffel Tower, Louvre, ตั๋วสวนสนุก
[Step 3] หยุดพักและคิดทบทวน (planning interval) โรงแรมแพงเกินไป -> งบเกิน ควรหาตัวเลือกที่ถูกกว่า + กิจกรรมสำหรับเด็ก
[Step 4] ค้นหา "affordable family hotels in Europe" -> พบตัวเลือกระดับกลางในหลายเมือง

def callback_function(agent_step, agent):
# Do something with the agent step or the agent itself
pass
agent_step: รายละเอียดของขั้นตอน (แผน, หมายเลขขั้นตอน ฯลฯ) agent: อ็อบเจกต์ agent ทั้งหมด (state + methods)def planning_callback(agent_step, agent):
print("AGENT PLANNING")
print("=" * 50)
print(agent_step.plan[:300])
if len(agent_step.plan) > 300:
print("\n... (plan truncated)")
print("=" * 50)
AGENT PLANNING
==================================================
Search affordable hotels + kid activities
Then create balanced itinerary...
... (plan truncated)
==================================================
def action_callback(agent_step, agent):
step_num = agent_step.step_number
print(f"Step {step_num}: Taking action")
if agent_step.is_final_answer:
total_tokens = agent_step.token_usage.total_tokens
print(f"Total tokens used: {total_tokens}")
Step 2: Taking action!
Step 3: Taking action!
Step 4: Taking action!
Total tokens used: 4,218
from smolagents import ActionStep, PlanningStep
agent = CodeAgent(
tools=[document_search_tool],
model=model,
step_callbacks={PlanningStep: planning_callback, ActionStep: action_callback}
)
AI Agents ด้วย Hugging Face smolagents