Skip to slide
027 / 221

CH 02 · The Agent Loop Pattern · 15/15

Read as one page

Read the source yourself

A reading tour, in order, that walks the loop from the outside in:

  1. The whole loop in one function. pi's runLoop is this chapter's pseudocode at production size. Find where hasMoreToolCalls is set and where turn_end is emitted, and map each to a line of the essential loop.
  2. A loop the library owns. The OpenAI Agents SDK's AgentRunner.run runs while True:. Follow what happens on a handoff (one agent passing control to another): the loop changes current_agent and goes round again.
  3. History repair before every request. Callers clone the history, then Codex's for_prompt takes that copy and normalizes it. List every rule normalize_history enforces.
  4. The other loop detector. Gemini CLI's checkContentLoop catches a model repeating the same text while it streams. Find why it switches itself off inside code blocks.

Exercise: write the essential loop from the start of this chapter as a small Python run_agent(model, tools, max_turns), then add three things from these repos: an "aborted" result for any call left without one, a cycle check for cycle lengths 1 to 3, and an on_max_turns callback that returns a message instead of a fixed string. Then write a fake model that alternates between two tool calls and confirm your detector stops it.

Finished this idea?

Your learning progress stays in this browser.