Skip to slide
021 / 170

CH 02 · The Agent Loop · 09/11

Read as one page

Read the source yourself

Four stops, smallest first. Each is the loop you built, with one more real problem solved.

  1. mini-swe-agent, src/minisweagent/agents/default.py. Read the file straight through. Then open interactive.py next to it and find which method InteractiveAgent overrides to ask you before a command runs.
  2. pi, packages/agent/src/agent-loop.ts. Trace one prompt through runLoop on paper: write down hasMoreToolCalls and pendingMessages after every lap of a two-tool-call task.
  3. pi, packages/agent/src/agent.ts. Find where getSteeringMessages and getFollowUpMessages are wired to the two queues. Then read continue(): what happens to queued messages when the last message in the history is the assistant's?
  4. Codex, codex-rs/core/src/session/turn.rs. In try_run_sampling_request, list every line that sets needs_follow_up to true. Expect tool calls and a denied or directly answered tool request (both arrive through output_result.needs_follow_up), an unfinished end_turn, and a few stream interruptions.

Exercise for you: give your agent_loop two upgrades from this chapter. First, make finishing a tool: add a submit tool, and treat a plain-text reply as an error you append to history and send back (mini-swe-agent's rule). Second, when fake_model returns "stop_reason": "length", append an error result for each tool call instead of running it (pi's rule). Script fake_model to hit both cases once and check that the loop recovers.

Finished this idea?

Your learning progress stays in this browser.