AI Agents with 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 pauses after every 3 steps."Plan a 2-week family vacation to Europe with historical sites for adults and fun activities for kids, staying under $5000."
[Step 1] Search "Paris hotels" -> Found luxury hotels (~$4000 total)
[Step 2] Search "Paris attractions for families" -> Found Eiffel Tower, Louvre, theme park tickets
[Step 3] Pause and rethink (planning interval) Hotels are too expensive -> budget blown. I should look for cheaper options + kid-friendly activities.
[Step 4] Search "affordable family hotels in Europe" -> Found mid-range options in multiple cities
def callback_function(agent_step, agent):
# Do something with the agent step or the agent itself
pass
agent_step
: details about the step (plan, step number, etc.) agent
: the full agent object (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 with Hugging Face smolagents