Stage 2 · Lesson 3 of 7
Writing the loop in code
Now write the loop for real with your provider's official in {choice}. Keep a list of messages. Call the model with the messages and tools.
Append the reply. If it asked for tools, run each one, append all the results in one message and loop. Otherwise return the text.
Give two or three simple tools real behaviour, such as reading a file of orders, so results are not faked. Print every call and result while you work, because watching the loop is how you learn it. Add a maximum number of steps from the start.
This small program, perhaps fifty lines, is the core that every framework in stage six wraps.
Common trapjumping to a framework before this works, and then being unable to tell whether a bug is yours or the framework's.
A question to check yourself, an AI practice session and 2 cheat sheet entries come with the full roadmap. Unlock
Resources for this stage
Start with· follow one of these
- GuideFreeClaude Tool Use Documentation
Anthropic · Intermediate
Read Overview, Define tools and Handle tool calls, then follow the tutorial that grows one call into a full loop
- GuideFreeOpenAI Function Calling Guide
OpenAI · Intermediate
The same loop on the Responses API: read it after your first provider to see what is universal