CH 02 · The Agent Loop Pattern · 15/15
Read as one pageRead the source yourself
A reading tour, in order, that walks the loop from the outside in:
- The whole loop in one function. pi's
runLoopis this chapter's pseudocode at production size. Find wherehasMoreToolCallsis set and whereturn_endis emitted, and map each to a line of the essential loop. - A loop the library owns. The OpenAI Agents SDK's
AgentRunner.runrunswhile True:. Follow what happens on a handoff (one agent passing control to another): the loop changescurrent_agentand goes round again. - History repair before every request. Callers clone the history, then Codex's
for_prompttakes that copy and normalizes it. List every rulenormalize_historyenforces. - The other loop detector. Gemini CLI's
checkContentLoopcatches 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.