Typorithm · medium

The Agent Loop

agent-loopllmagentloopstop-reason
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn The Agent Loop

0%

Tools & Agents

An agent is a loop: while the model's stop_reason is tool_use, run the requested tool, append the tool_result as a user turn, and call the model again. It ends when stop_reason becomes end_turn. Tools plus this loop enable autonomous multi-step tasks.

An agent is not magic — it is a loop around the same tool-calling request. Each response carries a stop_reason; while it equals tool_use, the model still wants to act.

On every pass you run the tool the model asked for, append the result as a user turn, and call the model again with the full updated message history. The model reads the result and decides what to do next.

The loop exits when stop_reason becomes end_turn, meaning the model is done and has produced its final answer. Tools give the model abilities; this loop lets it chain them into multi-step work.

01

Loop while stop_reason === "tool_use".

02

Run the tool, append the result, call again.

03

Exit when stop_reason becomes end_turn.

while (response.stop_reason === "tool_use") {
  const result = runTool(response.content);
  messages.push({ role: "user", content: [toolResult(result)] });
  response = await client.messages.create({ model, messages, tools });
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Loop condition

Keep looping while the model's stop_reason is tool_use — it still wants to call a tool.

while (response.stop_reason === "tool_use") {

2. Run the tool

runTool executes the requested tool against the model's tool_use block.

const result = runTool(response.content);

3. Append the result

The tool_result is appended as a user turn so the model sees the output.

messages.push({ role: "user", content: [toolResult(result)] });

4. Call again

Call the model again with the updated messages so it can take the next step.

response = await client.messages.create({ model, messages, tools });

5. Loop end

The loop exits once stop_reason is end_turn instead of tool_use.

}

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

The Agent Loop: Lesson & Practice · Typorithm | ApplyDjinn