Build the agent loop by hand
This is the one. In the next hour you write a working AI agent, by hand, with no framework helping you. It is about 20 lines.
What you are building
The five steps from the last lesson, as real Python:
- Call the model with your messages
- If it asks for a tool, run that tool
- Add the result to your messages
- Call the model again
- Stop when it replies without asking for anything
What you have been given
Two functions are ready for you. You do not need to write them.
chat(messages)sends the conversation to a model and returns its reply. It talks to a recorded answer, so there is no account and no cost.execute_tool(name, args)runs a tool and returns the result as text.
The tool in this lesson is a calculator. The model will ask you to work out 17 times 4.
Watch the Trace panel on the right while you run. Every step your code takes appears there in order. When something goes wrong, that panel is where you find out why.
Finish when
- Your loop asks for the
calculatortool - You add the result to
messagesbefore calling the model again - Your loop stops when the model asks for nothing
If your loop never stops, the page halts it after 8 model calls and tells you. Writing a loop with no exit is a rite of passage. Better here than in production.
The point
An agent is a while-loop around an AI model. You just built the thing that expensive courses charge for.
Check yourself
Answer out loud first. Reading the answer without trying is where the learning leaks out.
1. Which line makes this an agent rather than one model call?
2. Why append the assistant message with tool_calls before the tool result?
3. What does the step budget protect you from?