Reference ← Home

The universal loop, in about twelve lines.

Everything else is engineering. Put the bounded budget in from the start — retrofitting it after the first runaway is a rite of passage.

# The universal loop template
def agent_loop(goal, tools, verify, max_iter=10, budget_usd=0.50):
    context, spent, i = [], 0.0, 0
    while i < max_iter and spent < budget_usd:
        step, cost = model.plan(goal, context)      # reason
        result    = tools.run(step.tool_call)      # act
        context.append(step, result)              # observe
        spent += cost
        if verify(goal, context):               # stop condition
            return {"ok": True, "context": context, "cost": spent}
        i += 1
    return {"ok": False, "reason": "bounded", "cost": spent}