Agent Loop in Code
The core of the agent is a while loop:
- model returned
tool_calls→ execute tools, add results to themessageslist and continue; - no
tool_calls→ output the answer and finish.
The messages list grows continuously — the main job of the agent framework boils down to managing it: adding messages at the right time and sending the entire list to the model.
All context engineering techniques are essentially optimization of this list.
Related: ReAct Loop, Five Context Components