Controlling Loops of Agentic Tool-Use
Introduction: From Manual Steps to Automated Loops
In the previous lesson, you built a tool execution pattern where you made two separate API calls to complete a calculation task. This manual approach helped you understand context flow, but it is not practical for production systems where tasks might require many steps. In this lesson, you will build an agentic loop that automates this process, implementing Factor 8 (Own your control flow) by giving your code full control over execution, and Factor 9 (Compact Errors into Context Window) by feeding structured failure information back to the model. By the end, you will have an agent that handles multi-step tasks like "What is 15 + 27? Then multiply the result by 3" without any manual intervention.
Setting Up Loop Control Variables
Before building the loop, you need to establish control variables that manage execution boundaries and track progress. These variables implement Factor 8 by putting your code in charge of when the loop continues and when it stops.
These control variables work together to manage your agent's execution lifecycle:
- The
max_stepsvariable acts as a safety boundary that prevents runaway execution, which is critical for production systems where you need predictable resource usage and cost control. - The
stepcounter tracks how many iterations have occurred, helping with debugging and observability. - The
doneflag serves as your completion signal that gets set toTruewhen the model callsfinal_answer. - The
final_answervariable stores the result once it is provided.
The max_steps boundary is particularly important because it ensures your agent cannot consume unlimited API calls or compute resources. The combination of done and step gives you both logical completion (when the task finishes) and physical completion (when you hit resource limits), allowing your system to handle both successful completions and edge cases gracefully.
Building the While Loop Condition
The core agent loop uses a while condition that combines your completion flag and safety boundary to determine when execution should continue.
The condition not done and step < max_steps ensures that the loop stops either when the agent signals completion or when you hit your safety limit. At the start of each iteration, you increment the step counter and print a separator to make the execution flow visible during development.
