开始使用免费开始使用

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.

本练习是课程的一部分

AI Agents with Hugging Face smolagents

查看课程

练习说明

  • 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.

交互式实操练习

通过完成这段示例代码来试试这个练习。

# 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: {____}")
编辑并运行代码