Intermediate
Agents and tools

Writing an agent loop

The loop in forty lines, the tools it calls, and what it carries between turns.

What you will be able to do

Build an agent you can explain line by line, then decide whether a framework earns its place.

Prerequisites
Tool calling, from Calling a model from your own code.
Length
6 lessons · 25 min

Syllabus

  1. 1What are AI Agents?Anthropic's line is who decides what happens next: your code, or the model. The five workflow patterns that sit between one call and an agent, and the three costs the loop brings with it.3 min
  2. 2Manual ImplementationThe agent loop in forty lines, why a failing tool returns its error as a result, and what a framework is doing on top.6 min
  3. 3Tools & Function CallingThe model chooses a tool from its description alone, and every declaration is billed on every request whether or not it is called. Assume any tool with a side effect will be invoked twice.4 min
  4. 4Claude Agent SDKWriting the agent loop is straightforward; the harness supplies what surrounds it. Context management, sessions, permissions, and the file and shell tools an agent needs are what adopting the SDK gives you.4 min
  5. 5Context EngineeringFive things make up the payload, and each is a decision with its own failure. Tool definitions are billed on every call whether used or not.4 min
  6. 6State & Historical ContextTwenty turns into a booking, six settled facts are what the model needs and the transcript is an inefficient way to carry them. Trimming a turn per request can also cost more than sending everything, because it breaks the cache.4 min