Agent Loop in Code
The core of the agent is a while loop: if the model returned tool_calls – execute the tools, add the results to the messages list, and continue; if there are no tool_calls – output the answer and finish. The messages list grows continuously. The main job of the agent framework is managing this list: 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]