Building with AILesson 27 of 80

Module 3 · Structure, tools and the loop

Writing the loop, with the stopping conditions

In this lesson

  • 10 min read
  • 7 reading sections
  • Knowledge check
  • Lesson 7 of 11 in this chapter

This chapter’s goalDesign a schema and a tool surface a model can actually follow, write an agent loop with a step budget and a validated boundary at every hop, and say for each failure in that loop whether it should be retried, escalated to a human, or must stop the run.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmNot availableNot available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 8Free · no account needed
Lesson steps

Forty lines, and every line is a decision

Python
def run(task, tools, max_steps=8, max_cost=0.50, deadline_s=60):
    msgs = [{"role": "user", "content": task}]
    spent, started = 0.0, time.monotonic()

    for step in range(max_steps):
        r = llm.complete(SYSTEM, msgs, tools=tools)
        spent += cost_of(r.usage)
        msgs.append({"role": "assistant", "content": r.content})

        if r.stop_reason != "tool_use":
            return Done(text(r), steps=step + 1, cost=spent)

        results = []
        for call in tool_calls(r):
            if call.name not in tools:
                results.append(err(call, "unknown tool"))
                continue
            try:
                results.append(ok(call, tools[call.name](**call.args)))
            except ToolError as e:
                results.append(err(call, str(e)))     # recoverable, tell the model
        msgs.append({"role": "user", "content": results})

        if spent > max_cost:
            return Stopped("budget", msgs, spent)
        if time.monotonic() - started > deadline_s:
            return Stopped("deadline", msgs, spent)
        if repeating(msgs):
            return Stopped("loop detected", msgs, spent)

    return Stopped("step limit", msgs, spent)

That is the whole thing. Everything sold as an agent framework is this loop with conveniences around it. Writing it yourself once is worth more than reading three framework tutorials, because every interesting decision is visible.

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Every lesson here is open. Your progress is recorded once you pass the Python, from Zero, for AI exam.

Stuck on something?Ask Sayali, your AI tutor

How to cite: Addaly (2026) ‘Writing the loop, with the stopping conditions’, in Building with AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/building-with-ai/writing-the-agent-loop (Accessed: 29 November 2026).