Get startedGet started for free

Track Agent Steps, Monitor the Action

You're building a smolagents assistant for a basketball coach who needs help analyzing PDF reports that contain player stats, scouting insights, and game strategies.

The coach relies on the agent to answer questions like: "What defensive strategies should we run against their second unit?"

But the coach doesn't just want answers — they want visibility into what the agent is doing behind the scenes.

In this exercise, you'll write an action callback that runs every time the agent takes a step, such as calling a tool or using the model. This callback will:

  • Show the number of steps,
  • And if the agent has finished, display how many tokens were used.

This will help the coach (and you!) monitor how the agent is progressing and how much work it's doing to reach a conclusion.

This exercise is part of the course

AI Agents with Hugging Face smolagents

View Course

Exercise instructions

  • Complete the function signature by adding the agent_step parameter.
  • Check whether the current step produced a final answer using the .is_final_answer attribute of agent_step.
  • If it's the final answer, get the total number of tokens from total_tokens and print it.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Define an action callback that accepts the agent step and the agent
def action_callback(____, agent):
    step_num = agent_step.step_number
    print(f"Step {step_num}: Analyzing basketball data!")
    
    # Check if the agent step includes token usage
    if agent_step.____:
        total_tokens = agent_step.token_usage.total_tokens
        # Print how many tokens were used
        print(f"Analysis complete! Total tokens used: {____}")
Edit and Run Code