Skip to content

< all problems31 · Level 05, Agents

Write a Ralph Loop From Scratch

medium · implement · Agents

A Ralph loop (Geoffrey Huntley's name for it) is a while loop that feeds the model the same prompt every iteration against a fresh context. Progress lives in the state, not the conversation: each iteration reads the state, does one thing, writes it back, and exits.

Implement ralph(llm, task_list, max_iterations=10):

  1. While there are unfinished tasks and iterations remain:
    • Build a prompt from the current state: the task list with each item's status.
    • Ask the model which single task to do next, and mark it done.
    • Update the state.
  2. Return the final state.

Two rules:

One task per iteration. A prompt asking for everything at once is a normal agent call with extra ceremony.

The loop must terminate. Two conditions, both required: all tasks done, or the iteration cap. Ralph's failure mode is running forever at real cost, so max_iterations is part of the design.

You are scored on model_calls. An implementation that re-does completed tasks still terminates and still costs more than one that does not.