A Minimal Agent Loop in 60 Lines
Write a complete tool-using agent loop from scratch and see exactly how messages, tool calls, and results flow.
Agent frameworks can make agents look like magic: you hand over a prompt and some functions, and somehow the model "uses tools." There's no magic. There's a loop, maybe 25 lines long, that you can read top to bottom and fully understand.
In this lesson you'll write that loop yourself: a complete tool-using agent in about 60 lines of TypeScript, with a Python version alongside. You'll run it, read the exact messages that flow between your code and the model, and learn the three rules that every tool-calling agent must follow. Once you've written this loop, every agent product you use will make more sense, and you'll know exactly where to look when one misbehaves.
The whole idea in one picture
You met the agent loop conceptually in The Agent Loop: Think, Act, Observe. In code, it looks like this:
messages = [user task]
loop:
response = call the model with messages and tool descriptions
append response to messages
if response.stop_reason is not "tool_use":
return the text <- the model is done
for each tool_use block in response:
run the tool in your code
append ONE user message with all the tool_result blocksThe model never runs anything. It only asks for a tool by returning a tool_use block with a name and some JSON input. Your code runs the tool and sends back a tool_result. The model reads the result and decides what to do next: call another tool, or answer. That's the entire mechanism.
Our first agent gets two deliberately small tools: one that reads the clock in any time zone and one that does exact arithmetic. They're simple enough to understand at a glance, yet together they answer questions the model can't answer alone, such as "how many minutes until midnight in Tokyo?" The model doesn't know the current time, and it shouldn't do arithmetic in its head when a tool can do it exactly.